我正在尝试解析一个非常广泛的HTML文档,它看起来像:
<br>
<div class="reportsubsection n" ><br>
<h2> 1.4 Test </h2><br>
<p> insert text here </p ><br>
<table> crazy table thing here < /table ><br>
</div>
<div class="reportsubsection n"><br>
<h2> 1.4 Finding < /h2 ><br>
<p> insert text here < /p ><br>
<table> crazy table thing here < /table><br>
</div>
我需要在具有文本"Finding"的h2
的基础上解析出第二个div
。我能够用破解所有div
标签
divTag = soup.find("div", {"id": "reportsubsection"})
但不知道如何将其缩小。根据我发现的其他帖子,我能够找到特定的文本"第2部分,但我需要能够打印它包含的整个div
部分。基本上,如果div
有class=reportsubsection
,而h2
有单词"Finding",则打印整个"div"。
我根据我发现的其他帖子尝试了以下内容,但没有返回任何结果。
divTag = soup.find("div", {"id": "reportsubsection"})
for reportsubsection in soup.select('div#reportsubsection #reportsubsection'):
if not reportsubsection.findAll('h2', text=re.compile('Finding')):
continue
print divTag
您正在查找id
设置为'reportsubjection'的div
元素。但在HTML中,值为"reportsubjection"的是div
的class
属性。
试试这个:
>>> from bs4 import BeautifulSoup as bs
>>> data = '''<div class="reportsubsection n" ><br>
... <h2> 1.4 Test </h2><br>
... <p> insert text here </p><br>
... <table> crazy table thing here </table><br>
... </div>
... <div class="reportsubsection n"><br>
... <h2> 1.4 Finding </h2><br>
... <p> insert text here </p><br>
... <table> crazy table thing here </table><br>
... </div>'''
>>> soup = bs(data)
>>> div_tag = soup.find_all("div", {"class": "reportsubsection n"})
>>> for tag in div_tag:
... if 'Finding' in tag.h2.text:
... print tag.text
...
1.4 Finding
insert text here
crazy table thing here