我正在试着抓取一个维基百科的页面。面对一个简单的问题,却找不到解决方案。th和td的两个标签彼此相邻。而且,它们都是独立的。我想根据其他标记的值(彼此独立)来获取1标记的文本。
下面是一个示例:
<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亿美元)。记住,唯一的对应关系是“彼此紧挨着”。
发布于 2016-12-10 15:31:53
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)输出:
$200 million[3]https://stackoverflow.com/questions/41072948
复制相似问题