我已经编写了第一段 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")
return None
因为该文档是您意想不到的。
您应该确保可以在服务器上获取您尝试获取的页面,或者正确处理异常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)