Python - 属性错误 : 'NoneType' object has no attribute 'findAll'

标签 python attributes findall nonetype

我已经编写了我的第一段 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/

相关文章:

jquery - 使用 jQuery 删除 html5 必需属性

class - 如何间接访问类的属性

python - find_all 具有多个属性

php - CakePHP 中的 $data findAll 查询检查第二个表中的值

python - 随机生成更多比例的零python

python - 索引超出范围错误(从文件读取的数组)

python - Google身份验证问题: Authorized user info was not in the expected format,缺少字段refresh_token

python - 异常值分析 Python : Is there a better/more efficient way?

C#:一个属性用于多个声明 (DLLImport)

Python 和 BeautifulSoup - 我可以重复使用函数 find_All 吗?