2012-07-26 101 views
0

我有下面的代码:美丽的汤臭虫?

for table in soup.findAll("table","tableData"): 
    for row in table.findAll("tr"): 
     data = row.findAll("td") 
     url = data[0].a 
     print type(url) 

我得到一个输出:

<class 'bs4.element.Tag'> 

这意味着,网址是类标签的对象,我可以从这个对象获得attribytes。 但是,如果我更换print type(url)print url['href']我得到下一个回溯

Traceback (most recent call last): 
File "baseCreator.py", line 57, in <module> 
    createStoresTable() 
File "baseCreator.py", line 46, in createStoresTable 
    print url['href'] 
TypeError: 'NoneType' object has no attribute '__getitem__' 

有什么不对?以及我如何获得href属性的值。

+2

你有一个循环;你确定*所有* tr> td元素都有''标签吗? – 2012-07-26 17:58:00

+0

谢谢,你是对的。页面包含非常大的表格,每行都有网址。但是当我仔细地看着我发现,在一行网址丢失。 – KoirN 2012-07-26 18:34:13

回答

2

我喜欢BeautifulSoup,但我个人更喜欢lxml.html(不太多古怪 HTML)的,因为利用的XPath的能力。

import lxml.html 
page = lxml.html.parse('http://somesite.tld') 
print page.xpath('//tr/td/a/@href') 

尽管取决于结构,可能需要实现某种形式的“轴”。

您还可以使用elementsoup作为一个解析器 - 细节在http://lxml.de/elementsoup.html

+0

lxml也有一个美丽的后端。 – Marcin 2012-07-26 18:17:45

+0

@Marcin好的一点,我忘了提及soupparser - 更新,谢谢。 – 2012-07-26 18:20:48