我已经编写了我的第一段 python 代码来抓取网站。
import csv
import urllib2
from BeautifulSoup import BeautifulSoup
c = csv.writer(open("data.csv", "wb"))
soup = BeautifulSoup(urllib2.urlopen('http://www.kitco.com/kitco-gold-index.html').read())
table = soup.find('table', id="datatable_main")
rows = table.findAll('tr')[1:]
for tr in rows:
cols = tr.findAll('td')
text = []
for td in cols:
text.append(td.find(text=True))
c.writerow(text)
当我在名为 pyCharm 的 ide 中对其进行本地测试时,它运行良好,但是当我在运行 CentOS 的服务器上进行测试时,出现以下错误:
domainname.com [~/public_html/livegold]# python scraper.py
Traceback (most recent call last):
File "scraper.py", line 8, in <module>
rows = table.findAll('tr')[:]
AttributeError: 'NoneType' object has no attribute 'findAll'
我猜我没有远程安装模块,我已经挂断了这两天任何帮助将不胜感激! :)
最佳答案
您将忽略 urllib2.urlopen
中可能发生的任何错误,如果由于某种原因您在尝试获取服务器上的该页面时遇到错误,而您没有在本地进行测试,那么您有效地将空字符串 (''
) 或您不希望的页面(例如 404 页面)传递给 BeautifulSoup
。
这反过来又使您的 soup.find('table', id="datatable_main")
返回 None
因为该文档是您不期望的。
您应该确保您可以在您的服务器上获取您尝试获取的页面,或者正确处理异常。
关于Python - 属性错误 : 'NoneType' object has no attribute 'findAll' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065768/