漂亮的汤虫?

2024-04-26 23:12:46 发布

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

我有下一个代码:

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

我得到下一个输出:

^{pr2}$

这意味着,这个url是类标记的对象,我可以从这个对象中获取属性。 但如果我将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属性的值。在


Tags: 对象inpyurlfordata属性type
1条回答
网友
1楼 · 发布于 2024-04-26 23:12:46

我确实喜欢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

相关问题 更多 >