在使用 beautifulsoup 解析 html 中的表格时,每隔一行以
<tr class="row_k">
而不是没有类的 tr 标签
示例 HTML
<tr class="row_k">
<td><img src="some picture url" alt="Item A"></td>
<td><a href="some url"> Item A</a></td>
<td>14.8k</td>
<td><span class="drop">-555</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="Max llll">
</td>
</tr>
<tr>
<td><img src="some picture url" alt="Item B"></td>
<td><a href="some url"> Item B</a></td>
<td>64.9k</td>
<td><span class="rise">+165</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="max llll">
</td>
</tr>
<tr class="row_k">
<td><img src="some picture url" alt="Item C"></td>
<td><a href="some url"> Item C</a></td>
<td>4,000</td>
<td><span class="rise">+666</span></td>
<td>
<img src="some picture url" title="stuff">
</td>
<td>
<img src="some picture url" alt="Maximum lllle">
我要提取的文本是 14.8k、64.9k 和 4,000
this1 = urllib2.urlopen('my url').read()
this_1 = BeautifulSoup(this1)
this_1a = StringIO.StringIO()
for row in this_1.findAll("tr", { "class" : "row_k" }):
for col in row.findAll(re.compile('td')):
this_1a.write(col.string if col.string else '')
Item_this1 = this_1a.getvalue()
我觉得这段代码写得不好,有没有更灵活的工具可以使用,比如 XML 解析器?有人可以建议。
仍然对仍然使用 beautifulsoup 的任何答案持开放态度。
最佳答案
我仍在学习很多东西,但我建议您尝试 lxml。我将对此进行尝试,我认为它主要会让你到达那里,但可能有一些我不确定的细节。
假设this1是一个字符串
from lxml.html import fromstring
this1_tree=fromstring(this1)
all_cells=[(item[0], item[1]) for item in enumerate(this1_tree.cssselect('td'))] # I am hoping this gives you the cells with their relative position in the document)
我唯一不能完全确定的是,您是否测试每个单元格的键或值或 text_content 以查明它是否具有您在 anchor 引用或文本中查找的字符串。这就是为什么我想要您的 html 样本的原因。但是其中一个应该可以工作
the_cell_before_numbers=[]
for cell in all_cells:
if 'Item' in cell[1].text_content():
the_cell_before_numbers.append(cell[0])
现在您已经有了单元格,然后可以通过获取下一个单元格的文本内容来获取所需的值
todays_price=all_cells[the_cell_before_number+1][1].text_content()
我相信有更漂亮的方法,但我认为这会让你到达那里。
我使用您的 html 进行了测试,得到了您想要的内容。
关于python - 我如何阻止漂亮的汤在解析时跳过行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2394300/