【发布时间】: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>
我关心的唯一价格是那些与具有“正常价格”作为文本的元素配对的价格。
我想做的是扫描表的后代,找到包含该文本的 <td> 标记,然后从它的兄弟中提取文本。
我遇到的问题是,在 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)
我什么也得不到。有没有简单的方法来取回字符串值?
【问题讨论】:
-
我刚跑了这个,我得到了
<td class="another-class">$100.00</td>;我错过了什么吗? -
是的。我也没有得到一些东西。我发现
Tag在那里,但它不是下一个兄弟姐妹。下一个兄弟是回车。
标签: python html web-scraping beautifulsoup