我正在做网页抓取这个页面http://www.crmz.com/Directory/Industry806.htm,我应该得到所有的
-
#
-
公司名称
-
国家
-
州/省
但是compnay名称旁边有一个rss链接,所以我没有得到结果并显示一个typeError .
这是我的代码:
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
mech = Browser()
url = "http://www.crmz.com/Directory/Industry806.htm"
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
table = soup.find("table", {"border":"0", "cellspacing":"1", "cellpadding":"2"})
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
text = ''.join(td.find(text=True))
print text+"|",
print
这是我的输出:
LRI$ python scrape.py
#| Company Name| Country| State/Province|
1.| 1300 Smiles Limited|
Traceback (most recent call last):
File "scrape.py", line 17, in <module>
text = ''.join(td.find(text=True))
TypeError
2 回答
尝试加入文本搜索的
None
值会导致异常:这里的
None
是触发异常的原因:那是因为
.find()
只会找到 first 文本对象,或者如果没有这样的对象则返回None
. 您可能打算使用td.findAll(text=True)
,它将始终返回一个列表:或者更好的是,使用
tag.getText()
方法:我强烈建议你改用BeautifulSoup 4; BeautifulSoup 3现在已经超过2年没有看到任何错误修复或其他维护 .
您可能还想查看csv module来编写输出 .
你应该更换
同
因为
text
属性的输入是一个字符串