使用beautifulSoup和prin访问属性

2024-10-01 13:28:25 发布

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

我想刮一个网站,以查找所有标题属性的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})没有结果。我做错什么了?如何在文件中打印整个标题列表


Tags: importhttpurl标题titleexamplehtmlpage
2条回答

问题是title不是h2标记的属性,而是包含在其中的标记的属性。因此,必须首先搜索<h2>标记,然后搜索具有title属性的子标记:

titles = []
h2_list = links = soup.findAll('h2')
for h2 in h2_list:
    titles.extend(h2.findAll(lambda x: x.has_attr('title')))

这是因为BeautifulSoup可以使用函数作为搜索过滤器

您需要在attrs中传递键值对

findAll('h2', attrs = {"key":"value"}) 

相关问题 更多 >