使用beautifulSoup和print访问属性

时间:2018-03-30 09:25:48

标签: python beautifulsoup

我想抓一个网站找到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'})没有结果。我究竟做错了什么?如何在文件中打印出整个标题列表?

2 个答案:

答案 0 :(得分:1)

问题是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可以使用函数作为搜索过滤器。

答案 1 :(得分:0)

您需要在attrs中传递键值对

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