【问题标题】:Beautiful soup find_all doesn't find CSS selector with multiple classes美丽的汤 find_all 找不到具有多个类的 CSS 选择器
【发布时间】:2018-09-11 04:00:18
【问题描述】:

网站上有这个<a>元素

<a role="listitem" aria-level="1" href="https://www.rest.co.il" target="_blank" class="icon rest" title="this is main title" iconwidth="35px" aria-label="website connection" style="width: 30px; overflow: hidden;"></a>

所以我用这段代码来捕捉元素
(注意 find_all 参数 a.icon.rest

import requests
from bs4 import BeautifulSoup

url = 'http://www.zap.co.il/models.aspx?sog=e-cellphone&pageinfo=1'
source_code = requests.get(url)
plain_text = source_code.text
soup  = BeautifulSoup(plain_text, "html.parser")
for link in soup.find_all("a.icon.rest"):
    x = link.get('href')
    print(x)

不幸的是,它什么也没返回
尽管美丽的汤文档清楚地表明:

如果你想搜索匹配两个或更多 CSS 类的标签,你 应该使用 CSS 选择器:

css_soup.select("p.strikeout.body")
returns: &lt;p class="body strikeout"&gt;&lt;/p&gt;

那么为什么这不起作用? 顺便说一句,我用的是pycharm

【问题讨论】:

    标签: python beautifulsoup css-selectors


    【解决方案1】:

    正如您引用的文档所解释的,如果您想搜索匹配两个 CSS 类的标签,您必须使用 CSS 选择器而不是 find_all。您引用的示例显示了如何做到这一点:

    css_soup.select("p.strikeout.body")
    

    但你没有这样做;无论如何你都使用了find_all,当然它没有用,因为find_all 没有使用CSS 选择器。

    将其更改为使用select,它确实需要一个 CSS 选择器,它会起作用。

    【讨论】:

    • 很难不混淆,因为文档中的这一行在解释find_all()的章节中间使用了select()
    猜你喜欢
    • 2020-12-31
    • 2020-03-15
    • 2021-07-14
    • 2023-04-03
    • 2016-09-26
    • 2021-06-04
    • 2018-04-18
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多