如何在BeautifulGroup中查找<div><span>text</span></div>的文本?

2024-05-16 15:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这是HTML:

<div><div id="NhsjLK">
<li class="EditableListItem NavListItem FollowersNavItem NavItem not_removable">
<a href="/profile/Dileep-Sankhla/followers">Followers <span class="list_count">92</span></a></li></div></div>

我想提取文本92,并将其转换为整数并用python2打印。我怎么能? 代码:

^{pr2}$

Tags: dividhtmlnotliprofileclasshref
1条回答
网友
1楼 · 发布于 2024-05-16 15:49:00

我不想直接通过类获取它,因为我认为“list_count”太宽泛了,可能会用于页面上的其他事情。在

单从这个HTML片段来看,肯定有几种不同的选择,但就我个人而言,最好的选择之一是使用“Followers”文本/标签并获得它的下一个兄弟:

from bs4 import BeautifulSoup

data = """
<div><div id="NhsjLK">
<li class="EditableListItem NavListItem FollowersNavItem NavItem not_removable">
<a href="/profile/Dileep-Sankhla/followers">Followers <span class="list_count">92</span></a></li></div></div>"""

soup = BeautifulSoup(data, "html.parser")
count = soup.find(text=lambda text: text and text.startswith('Followers')).next_sibling.get_text()
count = int(count)
print(count)

或者,另一种非常简洁可靠的方法是对父元素ahref值使用部分匹配(下面的*=部分):

^{pr2}$

或者,您可以检查父元素li的类值:

count = int(soup.select_one("li.FollowersNavItem .list_count").get_text())

相关问题 更多 >