【问题标题】:Get contents of a particular row获取特定行的内容
【发布时间】:2019-10-16 19:24:01
【问题描述】:

我想在文本为“xyz”的地方找到“td”,以便在该行中找到其他属性。我只有 'xyz' 并想在该行中获取其他元素。

.
.
.

<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>

.
.
.

我可以通过使用轻松获得“xyz”

required = soup.find('a', text = 'xyz')
print(required[0].text)

但我无法找到“td”,因此我可以使用find_next_siblings() 获取其他列。

预期输出:

xyz
address
phone number

【问题讨论】:

标签: python html web web-scraping


【解决方案1】:

使用 bs4 4.7.1 结合 :has:contains 的伪类来检索其中的行和 tds。

此位针对正确的 a 标记(如果其文本存在)

a:contains("xyz")

然后您检索具有此 a 标记的父行 (tr)

tr:has(a:contains("xyz"))

最后使用descendant combinatortd type selector 获取该行中的所有tds。使用列表推导返回列表。

from bs4 import BeautifulSoup as bs

html = '''
<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>
'''

soup = bs(html, 'lxml')
items = [item.text.strip() for item in soup.select('tr:has(a:contains("xyz")) td')]
print(items)

【讨论】:

    【解决方案2】:

    如果你有现代 BeautifulSoup,你可以使用 CSS 选择器:contains。然后用find_parent()方法回溯。

    from bs4 import BeautifulSoup
    
    s = '''
    <tr>
        <td>Other1</td>
        <td>Other1</td>
        <td>Other1</td>
    </tr>
    <tr>
        <td>
            <a>xyz</a>
        </td>
        <td>address</td>
        <td>phone number</td>
    </tr>'''
    
    soup = BeautifulSoup(s, 'lxml')
    
    for td in soup.select_one('a:contains(xyz)').find_parent('tr').select('td'):
        print(td.text.strip())
    

    打印:

    xyz
    address
    phone number
    

    【讨论】:

      【解决方案3】:

      用这个替换你的代码:

      from bs4 import BeautifulSoup
      
      html = '''<tr>
          <td>
              <a>xyz</a>
          </td>
          <td>address</td>
          <td>phone number</td>
      </tr>'''
      
      soup = BeautifulSoup(html, 'lxml')
      required = soup.find('a', text = 'xyz')
      print(required.text)
      td = required.parent
      siblingsArray = td.find_next_siblings()
      
      for siblings in siblingsArray:
          print(siblings.text)
      

      O/P:

      xyz
      address
      phone number
      

      其中parent 是获取直接父标签,find_next_siblings 返回下一个兄弟标签的列表。

      【讨论】:

        【解决方案4】:

        您可以使用 xpath。 find_elements_by_xpath().

        https://www.softwaretestingmaterial.com/how-to-locate-element-by-xpath-locator/
        

        【讨论】:

          猜你喜欢
          • 2011-02-25
          • 2012-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-05
          • 2016-06-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多