python3 nonetypefind_Python-AttributeError:“ NoneType”对象没有属性“ findAll”

I have written my first bit of python code to scrape a website.

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)

When I test it locally in my ide called pyCharm it works good but when I try it out on my server which runs CentOS, I get the following error:

domainname.com [~/public_html/livegold]# python scraper.py

Traceback (most recent call last):

File "scraper.py", line 8, in

rows = table.findAll('tr')[:]

AttributeError: 'NoneType' object has no attribute 'findAll'

I'm guessing I don't have a module installed remotely, I've been hung up on this for two days any help would be greatly appreciated! :)

解决方案

You are ignoring any errors that could occur in urllib2.urlopen, if for some reason you are getting an error trying to get that page on your server, which you don't get testing locally you are effectively passing in an empty string ('') or a page you don't expect (such as a 404 page) to BeautifulSoup.

Which in turn makes your soup.find('table', id="datatable_main") return None since the document is something you don't expect.

You should either make sure you can get the page you are trying to get on your server, or handle exceptions properly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值