2017-04-20 135 views
0

我使用BeautifulSoup解析通过html并试图检索标题。BeautifulSoup获得标题返回'NoneType'对象没有属性'__getitem__'

我的代码如下:

callerid = cell_list[0] 
print callerid.find('a') 

,返回的我想从我的提取“标题”适当的锚标记。

<a class="caller_ref" href="/tomasi/cardio/vgh/SPsdeGBHH" 
title="CDS1255S56d">identifier</a> 

现在,这里是它变得时髦。当我加入[“标题”]我的print语句来提取标题,

callerid = cell_list[0] 
print callerid.find('a')["title"] 

我得到

AttributeError: 'NoneType' object has no attribute 'find'

这怎么能是“NoneType”时,它显然包含了锚标记HTML如第一个例子所示,我如何解析它以返回标题?

+0

你可以在'callerid = cell_list [0]'后面加上'print callerid'并显示结果吗? – kvorobiev

+0

添加'[“标题”]'不会导致此错误。错误发生是因为'callerid'是'None'。 – kindall

+0

@kvorobiev是肯定的结果是 ' identifier' –

回答

0

callerid.find('a')应该是callerid.find('a').a['title']
它可能看起来像它,但callerid.find('a')实际上并不返回标签的内容! (其实the documentation并不至于什么它确实回报非常翔实的...?)

0

尝试,

from bs4 import BeautifulSoup 
content = '<a class="caller_ref" href="/tomasi/cardio/vgh/SPsdeGBHH" 
title="CDS1255S56d">identifier</a>' 
soup = BeautifulSoup(content) 
anchor = soup.find_all('a')[0] 
print "title : " + (anchor.get('title')) 
0

我赶上了错,我基本上是通过表解析与多个行,所有行都有锚标记,因此print callerid.find('a')可以工作。

但是至于print callerid.find('a')["title"]此行将返回NoneType,因为表i的第一行解析是唯一一行(19456行之外)没有标题标记,这会停止所有进一步的执行。

谢谢大家的帮助。

相关问题