Python - 如何在多个标签之间提取元素

时间:2015-08-16 10:03:00

标签: python html python-3.x beautifulsoup extract

正在使用的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
################

或类似的东西

0 个答案:

没有答案