使用BeautifulSoup查找具有特定孩子的元素 [英] Find elements which have a specific child with BeautifulSoup
本文介绍了使用BeautifulSoup查找具有特定孩子的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用BeautifulSoup,如何访问具有特定div
作为孩子的<li>
?
With BeautifulSoup, how to access to a <li>
which has a specific div
as child?
示例:如何访问以Email
作为子div的li
的文本(即info@blah.com)?
Example: How to access to the text (i.e. info@blah.com) of the li
which has Email
as child div?
<li>
<div>Country</div>
Germany
</li>
<li>
<div>Email</div>
info@blah.com
</li>
我尝试手动执行此操作:在所有li
上循环播放,对于每个li
,在所有子div
上重新循环播放,以检查文本是否为Email等,但是我确定存在一个带有BeautifulSoup的版本更加聪明.
I tried to do it manually: looping on all li
, and for each of them, relooping on all child div
to check if text is Email, etc. but I'm sure there exists a more clever version with BeautifulSoup.
推荐答案
有多种方法可以解决此问题.
There are multiple ways to approach the problem.
One option is to locate the Email
div by text and get the next sibling:
soup.find("div", text="Email").next_sibling.strip() # prints "info@blah.com"
这篇关于使用BeautifulSoup查找具有特定孩子的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文