正在使用的HTML:
<h2> Heading 1 </h2>
<h3> Subheading 1.1 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a> | <a href="#">Link 3</a>
<h3> Subheading 1.2 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a> | <a href="#">Link 3</a> | <a href="#">Link 4</a>
<h3> Subheading 1.3 </h3>
<a href="#">Link 1</a>
<h2> Heading 2 </h2>
<h3> Subheading 2.1 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2</a>
<h3> Subheading 2.2 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a>
<h3> Subheading 2.3 </h3>
<a href="#">Link 1</a>
<h2> Heading 3 </h2>
问题:
我想在每个h3
代码之间提取h2
代码,并在anchors
代码之间提取所有h3
我有什么:
soup = BeautifulSoup("""<h2> Heading 1 </h2>
<h3> Subheading 1.1 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a> | <a href="#">Link 3</a>
<h3> Subheading 1.2 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a> | <a href="#">Link 3</a> | <a href="#">Link 4</a>
<h3> Subheading 1.3 </h3>
<a href="#">Link 1</a>
<h2> Heading 2 </h2>
<h3> Subheading 2.1 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2</a>
<h3> Subheading 2.2 </h3>
<a href="#">Link 1</a> | <a href="#">Link 2 </a>
<h3> Subheading 2.3 </h3>
<a href="#">Link 1</a>
<h2> Heading 3 </h2>""", 'html5lib')
for row in soup.find_all("h2"):
print(row.text)
print(row.find_next('h3'))
print('################')
当前结果:
################
Heading 1
<h3> Subheading 1.1 </h3>
################
Heading 2
<h3> Subheading 2.1 </h3>
################
Heading 3
None
################
通缉结果:
################
Heading 1
Subheading 1.1
Link 1
Link 2
Link 3
--------
Subheading 1.2
Link 1
Link 2
Link 3
Link 4
--------
Subheading 1.3
Link 1
################
Heading 2
Subheading 2.1
Link 1
Link 2
--------
Subheading 2.2
Link 1
Link 2
--------
Subheading 2.3
Link 1
################
或类似的东西