这是从一个有2个类属性的标签中获取项目的方法正确吗?

2024-10-04 01:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从带有BeautifulSoup的网站获取项目。在

<div class="post item">

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

首先,我写道

^{pr2}$

但是,这没用。 然后我写道

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

我不确定这是否正确。 这个代码正确吗?在

///额外的///

对不起

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

没有正常工作。 它还提取class="item"。在

而且,我不得不写信

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

不是=,而是_=。虽然这对我不起作用…(>;)

目标url:

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()

Tags: httpsdiv目标mainhtml标签allfind
2条回答

您可以使用css select:

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

或使用class_

^{pr2}$

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

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

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

首先,请注意class是一个非常特殊的multi-valued attribute,它是{}中常见的混淆源。在

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

这将找到所有具有post类或{}类(当然,也可以两者兼有)的div元素。这可能会产生您不想看到的额外结果,假设您使用严格的div元素class="post item"。如果是这种情况,可以使用CSS选择器:

html.select('div[class="post item"]')

在一个类似的主题中还有一些更多的信息:

相关问题 更多 >