python - 这种从具有 2 个类属性且 BeautifulSoup 的标签获取项目的方法是否正确?

标签 python beautifulsoup

我想通过 BeautifulSoup 从网站获取项目。

<div class="post item">

目标标签是这个。 该标签有两个属性和空白。

首先,我写道,

roots = soup.find_all("div", "post item")

但是,它不起作用。 然后我写道,

html.find_all("div", {'class':['post', 'item']})

我可以用这个得到元素,但我不确定这是否正确。 这段代码正确吗?

////附加////

对不起,

html.find_all("div", {'class':['post', 'item']})

无法正常工作。 它还提取 class="item"

而且,我必须写,

soup.find_all("div", class_="post item")

不是=而是_=。虽然这对我不起作用...(>_<)

目标网址:

https://flipboard.com/section/%E3%83%8B%E3%83%A5%E3%83%BC%E3%82%B9-3uscfrirj50pdtqb

我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from urllib.request import urlopen
from bs4 import BeautifulSoup

def main():
    target = "https://flipboard.com/section/%E3%83%8B%E3%83%A5%E3%83%BC%E3%82%B9-3uscfrirj50pdtqb"
    html = urlopen(target)
    soup = BeautifulSoup(html, "html.parser")
    roots = soup.find_all("div", class_="post item")
    print(roots)
        for root in roots:
            print("##################")


if __name__ == '__main__':
    main()

最佳答案

您可以使用 css 选择:

soup.select("div.post.item")

或者使用class_

.find_all("div", class_="post item")

文档建议*如果您想搜索与两个或多个 CSS 类匹配的标签,您应该按照第一个示例使用 CSS 选择器。 两种用途的示例:

您还可以搜索类属性的确切字符串值:

css_soup.find_all("p", class_="body strikeout")
# [<p class="body strikeout"></p>]

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

css_soup.select("p.strikeout.body")
# [<p class="body strikeout"></p>]

为什么你的代码会失败,以及上述任何解决方案都会失败,这更多地与该类在源代码中不存在这一事实有关,如果它们在那里,它们都会起作用:

In [6]: r = requests.get("https://flipboard.com/section/%E3%83%8B%E3%83%A5%E3%83%BC%E3%82%B9-3uscfrirj50pdtqb")

In [7]: cont = r.content

In [8]: "post item" in cont
Out[8]: False

如果您查看浏览器源代码并进行搜索,您也不会找到它。它是动态生成的,只有在打开开发者控制台或 firebug 时才能看到。它们还只包含一些样式和一个 React id,所以即使你确实得到了它们,也不确定你期望从中获取什么。

如果您想获取在浏览器中看到的 html,您将需要类似 selenium 的内容

关于python - 这种从具有 2 个类属性且 BeautifulSoup 的标签获取项目的方法是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254729/

相关文章:

python - opencv中的相机校准(Python立体相机)。错误:解包的值(value)太多

python - BeautifulSoup,简单的正则表达式问题

python - beautifulsoup find_all() 类快捷方式不起作用

Python 网页抓取; BeautifulSoup

python - 如何指定 virtualenv 的位置?

python - 如何从经过训练的 Spacy 模型中提取词嵌入向量

python - 如何在 TensorFlow 中导入模型

python - 仅当单独列中的差异在 [-n, +n] 范围内时,才在公共(public)列上加入两个 DataFrame

python - 网页抓取 : Table not included in BeautifulSoup Page

python - 仅从 BeautifulSoup 获取数字而不是整个 div