我想刮一个网站,以查找所有标题属性的h2标签
<h2 class="1"><a href="http://example.it/Titanic_Caprio.html" title="Titanic Caprio">Titanic_Caprio</a></h2>
使用这个代码,我访问整个h2标签
from bs4 import BeautifulSoup
import urllib2
url = "http://www.example.it"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
links = soup.findAll('h2')
print "".join([str(x) for x in links] )
使用findAll('h2',attrs={'title})没有结果。我做错什么了?如何在文件中打印整个标题列表
问题是
title
不是h2
标记的属性,而是包含在其中的标记的属性。因此,必须首先搜索<h2>
标记,然后搜索具有title
属性的子标记:这是因为BeautifulSoup可以使用函数作为搜索过滤器
您需要在attrs中传递键值对
相关问题 更多 >
编程相关推荐