python - 使用 find_parent 结果从中获取特定项目
问题描述
我正在努力寻找如何让它发挥作用。
我正在从网站上抓取少量数据,但内容放在没有类的 TABLE 中。关于那个问题,我正在运行它来找出我要搜索的单词在哪里:
item = soup.find_all(text=re.compile('WORD'))
然后,由于其他内容在同一个父项中,我这样做:
parent = item.find_parent('tr')
现在,我得到这样的东西:
<tr>
<td class="someclass1">WORD</td>
<td class="someclass2">TIRE</td>
<td class="someclass3">GUN</td>
<td class="someclass4">CAR</td>
<td class="someclass5">BYCICLE</td>
</tr>
既然它确实找到了 WORD 所在的好地方,我应该如何将 GUN 或 CAR 从中取出?正如我所说,这里的主要问题是,有多个表具有相同的 TD CLASSES,但其中只有 1 个具有 WORD。该表中的内容就是我要查找的内容。
解决方案
使用 bs4 4.7.1 +,您可以使用:contains
和:has
基于在WORD
表中具有给定类的元素中进行隔离。在您描述的情况下,您也可以:contains
直接工作,table
即table = soup.select_one('table:contains("WORD")')
。
from bs4 import BeautifulSoup as bs
html = '''
<html>
<head></head>
<body>
<table>
<tbody>
<tr>
<td class="someclass1">WORD</td>
</tr>
</tbody>
</table>
<table></table>
<table>
<tbody>
<tr>
<td class="someclass1">NOT_WORD</td>
</tr>
</tbody>
</table>
<table></table>
</body>
</html>
'''
soup = bs(html, 'lxml')
table = soup.select_one('table:has(.someclass1:contains("WORD"))')
print(table.text)
推荐阅读
- c# - 如何用c#连接到动态crm?
- javascript - 我如何获得单击哪个角色的值?
- c - 如果次正规数的存在是可选的(HAS_SUBNORM),那么为什么 FP_SUBNORMAL 的存在是强制性的?
- javascript - 使从绝对定位的 div 复制的文本保留空格
- php - Laravel Increment / Decrement 更新显示订单字段
- xbee - XBee S2C (XB24C) Router-Coordinator 不要发送或接收任何消息
- javascript - 在 WooCommerce 结帐页面中设置付款方式的样式(需要自定义 Javascript)
- javascript - 当时间超出其设定时间时如何关闭先前设定的间隔
- excel - 通过匹配范围中的字符串来过滤数据
- pine-script - 如何使用文本在交易视图图表中显示变量