我想从带有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()
您可以使用css select:
或使用class_
^{pr2}$文档建议*如果您想搜索匹配两个或更多CSS类的标记,您应该按照第一个示例使用CSS选择器。 两种用途的示例:
您还可以搜索class属性的确切字符串值:
如果要搜索匹配两个或多个CSS类的标记,应该使用CSS选择器:
为什么你的代码会失败为什么和上面的任何一个解决方案都会失败更多地与源代码中不存在类有关,如果在源代码中,它们都可以工作:
如果您查看浏览器源代码并进行搜索,您也不会找到它。它是动态生成的,只有在打开开发人员控制台或firebug时才能看到。它们也只包含一些样式和一个react id,所以即使你得到了它们,也不确定你期望从中得到什么。在
如果您想得到您在浏览器中看到的html,您需要类似selenium
首先,请注意}中常见的混淆源。在
class
是一个非常特殊的multi-valued attribute,它是{这将找到所有具有}类(当然,也可以两者兼有)的
post
类或{div
元素。这可能会产生您不想看到的额外结果,假设您使用严格的div
元素class="post item"
。如果是这种情况,可以使用CSS选择器:在一个类似的主题中还有一些更多的信息:
相关问题 更多 >
编程相关推荐