首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python抓取中查找彼此相邻的独立标记

问在python抓取中查找彼此相邻的独立标记
EN

Stack Overflow用户
提问于 2016-12-10 14:44:49
回答 1查看 25关注 0票数 0

我正在试着抓取一个维基百科的页面。面对一个简单的问题,却找不到解决方案。th和td的两个标签彼此相邻。而且,它们都是独立的。我想根据其他标记的值(彼此独立)来获取1标记的文本。

下面是一个示例:

代码语言:javascript
复制
<th scope="row" style="white-space:nowrap;padding-right:0.65em;">Budget</th>
<td style="line-height:1.3em;">$200 million<sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup></td>

如果'th‘标签文本是'Budget’,我想得到'td‘标签的值(它是2亿美元)。记住,唯一的对应关系是“彼此紧挨着”。

EN

回答 1

Stack Overflow用户

发布于 2016-12-10 15:31:53

代码语言:javascript
复制
from bs4 import BeautifulSoup

html = '''<th scope="row" style="white-space:nowrap;padding-right:0.65em;">Budget</th>
<td style="line-height:1.3em;">$200 million<sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup></td>'''

soup = BeautifulSoup(html, 'lxml')
td_text = soup.find(lambda tag: tag.name=='td' and 'Budget' in tag.parent.text).text
print(td_text)

输出:

代码语言:javascript
复制
$200 million[3]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41072948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档