python - 如何在 Beautiful Soup 中深入多个级别(find_all 错误)

标签 python python-3.x beautifulsoup

我试图在这个 Python 脚本中深入两个级别。我看到的所有示例都使用 find_all 向下钻取单个级别,并且我可以正常工作,但我无法深入到第三级别。这是我的代码片段:

main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
links = label_item_contents.find_all("a")
print(links)

这样做会出现错误“AttributeError:ResultSet 对象没有属性“find_all”。”

如果我注释掉并更改打印,那么就是这样:

main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
print(label_item_contents)

然后我看到了所有抓取的数据。我读到问题可能是 label_item_contents 变成了一个数组,所以我尝试这样做:

links = label_item_contents[].find_all("a")

但后来我得到“SyntaxError:无效语法”

感谢任何帮助!

编辑:这是当我使用 print(label_item_contents) 时在第二个示例中返回的 HTML 的一部分:

<div class="label-item-description">
    <div>
        <a href="/label/example.com"><strong>Example</strong></a>
    </div>
    <small>
        <i class="fa fa-facebook-official"></i> 342.4K
        <i class="fa fa-soundcloud"></i> 233.4K
    </small>
    <br />
    <small class="text-muted">
        Stockholm, Sweden
    </small>
    <br />
    <small class="text-muted">
        <b>Techno, Tech House</b>
    </small>
</div>, <div class="label-item-description">

我试图只访问 <a href="/label/example.com">

最佳答案

您可能想尝试一下 CSS 选择器——我发现它们更熟悉,而且重要的是,我发现它们导致的 AttributeError 问题更少。

例如,使用上面的html,您可以选择第一个 anchor 标记,如下所示:

link = soup.select("div.label-item-description > div > a")
print(link[0]) # <a href="/label/example.com"><strong>Example</strong></a>

查看文档:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

关于python - 如何在 Beautiful Soup 中深入多个级别(find_all 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606048/

相关文章:

python - 如何在 Python webapp (Google App Engine) 中导入 gflags?

python-3.x - Python、 PuLP : Turning a LpVariable into an integer

python - 沿二维数组中的对角线和反对角线求和 - NumPy/Python

python - 使用python抓取网页的问题

python - 在 Windows 上启动时运行 Python 程序

python - 由于 unicode 导致 u 导致 Doctest 失败

python - 从 Python 中的字符串中删除所有冠词、连接词等

python - 随机化字符串的大小写

python - 使用 beautiful soup 从 <td> 标签中提取正确格式的文本(中间有空格)

python - 如何将字符串转换为 BeautifulSoup 对象?