如何在beautifulsoup中查找<div><span>text</span></div>的文本?
How to find text of <div><span>text</span></div> in beautifulsoup?
这是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 中打印。我怎样才能?
代码:
i = soup.find('div', id='NhsjLK')
print "Followers :", i.find('span', id='list_count').text
我不会直接通过 class 获取它,因为我认为 "list_count" 的 class 值太宽泛,可能会用于页。
仅从这个 HTML 片段判断肯定有几个不同的选择,但从我的角度来看,最好的选择之一是使用 "Followers" text/label 并得到它的下一个兄弟姐妹:
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)
或者,另一种非常简洁可靠的方法是在 href
上使用 部分匹配 (下面的 *=
部分)父 a
元素的值:
count = int(soup.select_one("a[href*=followers] .list_count").get_text())
或者,您可以检查父 li
元素的 class 值:
count = int(soup.select_one("li.FollowersNavItem .list_count").get_text())
这是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 中打印。我怎样才能?
代码:
i = soup.find('div', id='NhsjLK')
print "Followers :", i.find('span', id='list_count').text
我不会直接通过 class 获取它,因为我认为 "list_count" 的 class 值太宽泛,可能会用于页。
仅从这个 HTML 片段判断肯定有几个不同的选择,但从我的角度来看,最好的选择之一是使用 "Followers" text/label 并得到它的下一个兄弟姐妹:
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)
或者,另一种非常简洁可靠的方法是在 href
上使用 部分匹配 (下面的 *=
部分)父 a
元素的值:
count = int(soup.select_one("a[href*=followers] .list_count").get_text())
或者,您可以检查父 li
元素的 class 值:
count = int(soup.select_one("li.FollowersNavItem .list_count").get_text())