python - 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>
解决方案
要搜索<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)
推荐阅读
- r - 过滤包含重要单核苷酸多态性的基因
- saml-2.0 - 单点注销如何与 OKTA(IDP)-Shibboleth(SP)-App 配合使用
- java - 如何在 Spring Boot 中对两个实体进行内部连接?
- javascript - 用于匹配第一个单词的正则表达式
- autodesk-forge - 尝试使用 Autodesk Forge ReCap API 重建特定数量的图像时出错
- python - TypeError:左操作数必须是 str
- postfix-mta - 带有多个接收字段的电子邮件标头:这怎么会发生,可以用来对抗垃圾邮件
- amazon-web-services - aws-cdk s3:PutBucketPolicy 部署具有公共读取访问权限的存储桶时访问被拒绝
- javascript - 使用 setTimeout 重复 xml 请求,尾调用优化?(在 js 中)
- javascript - 为什么这个画布动画偶尔会自己打乱?