【问题标题】:Find Text of Sibling Element, Where Original Element Matches Specific String查找同级元素的文本,其中原始元素与特定字符串匹配
【发布时间】:2016-05-23 01:05:09
【问题描述】:

我想从一堆 html 表中提取一些数据价格。表格包含各种价格,当然表格数据标签不包含任何有用的东西。

<div id="item-price-data">
  <table>
    <tbody>
      <tr>
        <td class="some-class">Normal Price:</td>
        <td class="another-class">$100.00</td>
      </tr>
      <tr>
        <td class="some-class">Member Price:</td>
        <td class="another-class">$90.00</td>
      </tr>
      <tr>
        <td class="some-class">Sale Price:</td>
        <td class="another-class">$80.00</td>
      </tr>
      <tr>
        <td class="some-class">You save:</td>
        <td class="another-class">$20.00</td>
      </tr>
    </tbody>
  </table>
</div>

我关心的唯一价格是那些与具有“正常价格”作为文本的元素配对的价格。

我想做的是扫描表的后代,找到包含该文本的 &lt;td&gt; 标记,然后从它的兄弟中提取文本。

我遇到的问题是,在 BeautifulSoup 中,descendants 属性返回NavigableString 的列表,而不是Tag

如果我这样做:

from bs4 import BeautifulSoup
from urllib import request

html = request.urlopen(url)
soup = BeautifulSoup(html, 'lxml')

div = soup.find('div', {'id': 'item-price-data'})
table_data = div.find_all('td')

for element in table_data:
    if element.get_text() == 'Normal Price:':
        price = element.next_sibling

print(price)

我什么也得不到。有没有简单的方法来取回字符串值?

【问题讨论】:

  • 我刚跑了这个,我得到了&lt;td class="another-class"&gt;$100.00&lt;/td&gt;;我错过了什么吗?
  • 是的。我也没有得到一些东西。我发现Tag 在那里,但它不是下一个兄弟姐妹。下一个兄弟是回车。

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可以使用find_next() 方法,也可能需要一些正则表达式:

演示:

>>> import re
>>> from bs4 import BeautifulSoup
>>> html = """<div id="item-price-data">
...   <table>
...     <tbody>
...       <tr>
...         <td class="some-class">Normal Price:</td>
...         <td class="another-class">$100.00</td>
...       </tr>
...       <tr>
...         <td class="some-class">Member Price:</td>
...         <td class="another-class">$90.00</td>
...       </tr>
...       <tr>
...         <td class="some-class">Sale Price:</td>
...         <td class="another-class">$80.00</td>
...       </tr>
...       <tr>
...         <td class="some-class">You save:</td>
...         <td class="another-class">$20.00</td>
...       </tr>
...     </tbody>
...   </table>
... </div>"""
>>> soup = BeautifulSoup(html, 'lxml')
>>> div = soup.find('div', {'id': 'item-price-data'})
>>> for element in div.find_all('td', text=re.compile('Normal Price')):
...     price = element.find_next('td')
...     print(price)
... 
<td class="another-class">$100.00</td>

如果您不想将正则表达式带入其中,那么以下内容将为您工作。

>>> table_data = div.find_all('td')
>>> for element in table_data:
...     if 'Normal Price' in element.get_text():
...         price = element.find_next('td')
...         print(price)
... 
<td class="another-class">$100.00</td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2016-06-25
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多