直到某一个使用beautifulsoup查找下一个兄弟姐妹 [英] Find next siblings until a certain one using beautifulsoup
本文介绍了直到某一个使用beautifulsoup查找下一个兄弟姐妹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的网页是这样的:
<h2>section1</h2>
<p>article</p>
<p>article</p>
<p>article</p>
<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
我怎样才能找到在其中的文章每节?即,发现H 2后,发现nextsiblings
,直到下一个H2
How can I find each section with articles within them? That is, after finding h2, find nextsiblings
until the next h2.
如果该网页是这样的:(这是通常的情况)
If the webpage were like: (which is normally the case)
<div>
<h2>section1</h2>
<p>article</p>
<p>article</p>
<p>article</p>
</div>
<div>
<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
</div>
我可以写codeS这样的:
I can write codes like:
for section in soup.findAll('div'):
...
for post in section.findAll('p')
但我应该用第一个网页做,如果我想获得相同的结果?
But what should I do with the first webpage if I want to get the same result?
推荐答案
我觉得你可以做这样的事情:
I think you can do something like this:
for section in soup.findAll('h2'):
nextNode = section
while True:
nextNode = nextNode.nextSibling
try:
tag_name = nextNode.name
except AttributeError:
tag_name = ""
if tag_name == "p":
print nextNode.string
else:
print "*****"
break
假设:
<h2>section1</h2>
<p>article1</p>
<p>article2</p>
<p>article3</p>
<h2>section2</h2>
<p>article4</p>
<p>article5</p>
<p>article6</p>
输出:
article1
article2
article3
*****
article4
article5
article6
*****
这篇关于直到某一个使用beautifulsoup查找下一个兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文