【发布时间】:2022-01-24 23:55:31
【问题描述】:
Beautiful soup: Extract everything between two tags
我通过上面的链接看到了一个问题,我们在其中获取了两个标签之间的信息。而当这些标签具有两个不同的 id 属性值时,我需要获取标签之间的信息。
<h1 id = 'beautiful' ></h1>
Text <i>here</i> has no tag
<div>This is in a div</div>
<h1 id = 'good' ></h1>
我正在使用 BeautifulSoup 从 HTML 文件中提取数据。我想获取两个标签之间的所有信息。这意味着如果我有这样的 HTML 部分:
<h1></h1>
Text <i>here</i> has no tag
<div>This is in a div</div>
<h1></h1>
如果我想要第一个 h1 和第二个 h1 之间的所有信息,输出将如下所示:
Text <i>here</i> has no tag
<div>This is in a div</div>
from bs4 import BeautifulSoup
html_doc = '''
This I <b>don't</b> want
<h1></h1>
Text <i>here</i> has no tag
<div>This is in a div</div>
<h1></h1>
This I <b>don't</b> want too
'''
soup = BeautifulSoup(html_doc, 'html.parser')
for c in list(soup.contents):
if c is soup.h1 or c.find_previous('h1') is soup.h1:
continue
c.extract()
for h1 in soup.select('h1'):
h1.extract()
print(soup)
打印:
Text <i>here</i> has no tag
<div>This is in a div</div>
这在没有 id 的情况下工作。
有人可以在这方面帮助我吗?
【问题讨论】:
标签: python html beautifulsoup tags