1 回答
TA贡献1936条经验 获得超6个赞
我能够find_previous在每个表上使用该方法来查找您提供的示例 html 的前一个标题。idx在检查标题是否属于该表时,我为每个表添加了一个附加属性。我还在 html 的开头和结尾添加了两个没有以前标题的表格。
html = '''
<table class='striped'></table>
<h3>
<span></span>
<span class='headline'>Headline #1</span>
</h3>
<table class='striped'></table>
<h4>
<span class='headline'>Headline #2</span>
</h4>
<table class='striped'></table>
<p>
<span class='headline'>Headline #3</span>
</p>
<ul></ul>
<center>
<table class='striped'></table>
</center>
<table class='striped'></table>
</div>
'''.replace('\n', '')
soup = BeautifulSoup(html, 'lxml')
table_query = ('table', {'class': 'striped'})
headline_query = ('span', {'class': 'headline'})
for idx, table in enumerate(soup.find_all(*table_query)):
table.attrs['idx'] = idx
previous_headline = table.find_previous(*headline_query)
if (previous_headline and
previous_headline.find_next(*table_query).attrs['idx'] == idx):
print(previous_headline.text)
else:
print('No headline found.')
输出:
No headline found.
Headline #1
Headline #2
Headline #3
No headline found.
添加回答
举报