<a href="link" target="_blank" class="xXx text-user topic-author" sl-processed="1">
diamonds
</a>
我想用 BeautifulSoup 提取“a”标签中的伪“钻石”。
我尝试了很多东西,但它总是返回“无”。
对我来说,应该工作的是这个
txt = soup.find('a', {'class': 'xXx text-user topic-author'})
print (txt)
最佳答案
看起来作者的 css 类在整个页面中都不相同,因此您需要进行一些过滤。
作者元素有多个 css 类,但它们有一些相似之处。
下面的代码将打印出作者。它首先获取作者所在的元素。问题是这个 css 类 (JvCare) 用于很多事情。元素计数为页面返回 98,但只有 25 个作者姓名,因此之后需要进行一些过滤。
import requests
from bs4 import BeautifulSoup
url = "http://www.jeuxvideo.com/forums/0-7059-0-1-0-1-0-another-war.htm"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
JvCs = soup.find_all('span', attrs={'class': 'JvCare'})
for j in JvCs:
if 'topic-author' in j['class']:
print(j.text.strip())
j['class'] 为 JvCs 列表中的 98 个元素中的每一个返回不同 css 类的列表。作者姓名所在的那些,有一个名为“主题作者”的 css 类。
所以我们只检查 'topic-author' 是否在 j['class'] 为 98 个元素中的每一个返回的列表中。如果是这样 - 打印作者姓名。
希望这能帮助你走得更远。
编辑: 对于涉及两个或多个 css 选择器的情况,似乎有一种更聪明的方法(在 BeautifulSoup 的非常棒的 docs 中提到)。在这些情况下,文档建议使用 .select-method。在你的情况下是这样的:
author_list = soup.select('span.JvCare.topic-author')
for author in author_list:
print(author.text.strip())
关于 python & BeautifulSoup : How to extract a tags' value which is in many others tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916585/