首页 > 解决方案 > Python Scraping:无论如何,我可以使用 beautifulsoup 来抓取这行代码吗?(查找包含特定标签/字符串的标签内容)

问题描述

假设源代码如下:

<tr> ... </tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr><td class="field2 mcFont" style="width: 220px; vertical-align:top">PE<div class="icon-edu icon-general-terms" style="display:none" data-key="PE Ratio"></div></td><td class="mcFont cls">7.18</td></tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr>

你好!我正在尝试使用beautifulsoup在表格行tr标签中抓取特定的代码行(请参见下面我想要实现的最终结果),但是由于tr标签不包含任何属性,而其他标签有数百万页面中的 tr 标签,无论如何我可以使用 soup.find_all("tr") 来抓取所有 tr 标签的内容,其中包括带有字符串“PE”或 class="field2 mcFont" 的 td 标签?

我想要达到的最终结果:

<td class="field2 mcFont" style="width: 220px; vertical-align:top">PE<div class="icon-edu icon-general-terms" style="display:none" data-key="PE Ratio"></div></td><td class="mcFont cls">7.18</td> 

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


要搜索<td>带有文本“PE”和下一个<td>标签(它的值)的标签,您可以使用:

from bs4 import BeautifulSoup

html_doc = """<tr> ... </tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr><td class="field2 mcFont" style="width: 220px; vertical-align:top">PE<div class="icon-edu icon-general-terms" style="display:none" data-key="PE Ratio"></div></td><td class="mcFont cls">7.18</td></tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr> ... </tr><tr>"""
soup = BeautifulSoup(html_doc, "html.parser")

pe = soup.find(lambda t: t.name == "td" and "PE" == t.text).find_next("td")
print(pe.text)

印刷:

7.18

或者使用 CSS 选择器:

pe = soup.select_one('td:-soup-contains("PE") + td')
print(pe.text)

推荐阅读