python & BeautifulSoup : How to extract a tags' value which is in many others tags?

标签 python css beautifulsoup

<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/

相关文章:

javascript - Mixitup - 未捕获的类型错误 : Cannot read property 'left' of undefined

html - 如何使用 CSS 在 anchor 上标文本中制作统一的下划线?

html - 列出带有直边框的 2 列中的元素

python - BeautifulSoup 将 HTML 解析为字典,其中 <h> 是键,<p> 是值

python - 使用 BeautifulSoup 获取结果集中 td 标签的文本

.net - 部署 IronPython 脚本或静态构建应用程序

python - 在 Python 中扩展一个数字 block

python - 如何使用 html5lib 解析 HTML,并使用 XPath 查询解析后的 H​​TML?

python - Pyramid :获取应用程序绝对 url

python - 当 xml 标签名称包含大写字母时,BeautifulSoup 引发 AttributeError