我已经编写了第一段 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
,因为该文档是您意想不到的。
您应该确保可以在服务器上获取您尝试获取的页面,或者正确处理异常。
脚本读取的页面中没有
table
和 id
datatable_main
。
尝试将返回的页面打印到终端 - 也许您的脚本无法联系网络服务器? 有时托管服务会阻止传出 HTTP 连接。
似乎 find_all 属性和 findall 根本不起作用,我正在编写一个 python 脚本,您在其中输入一个名称,它会从我的网站输出有关该名称的信息