我需要使我的代码向后兼容python2.6和BeautifulSoup 3.我的代码是使用python2.7编写的,在这种情况下使用BS4 . 但是当我尝试在squeezy服务器上运行它时,我得到了这个错误(它有python2.6和bs3):
try:
from bs4 import BeautifulSoup
except ImportError:
from BeautifulSoup import BeautifulSoup
gmp = open(fname, 'r')
soup = BeautifulSoup(gmp)
p = soup.body.div.find_all('p')
p = soup.body.div.find_all('p')
TypeError: 'NoneType' object is not callable
如果我改为:
p = soup.body.div.findAll('p')
然后我收到这个错误:
p = soup.body.div.findAll('p')
TypeError: 'NoneType' object is not callable
Update of thrown error
File "/home/user/openerp/7.0/addons/my_module/models/gec.py", line 401, in parse_html_data
p = soup.body.div.findAll('p') #used findAll instead of find_all for backwards compatability to bs3 version
TypeError: 'NoneType' object is not callable
无论哪种方式,这两种方法都可以在我的Ubuntu上运行python2.7和bs4,但不能用于squeezy . 那些我没有看到/知道的版本之间是否有任何其他差异并给我这个错误?
1 回答
您正在使用BeautifulSoup 3,但正在使用BeautifulSoup 4语法 .
你的后备是错误的:
如果要使用版本3或4,请坚持使用版本3语法:
因为
find_all
不是BeautifulSoup 3中的有效方法,所以它被解释为标签搜索 . 您的HTML中没有find_all
标记,因此会返回None
,然后您尝试调用它 .接下来,BeautifulSoup 3使用的解析器将对已损坏或不完整的HTML做出不同的响应 . 如果您在Ubuntu上安装了
lxml
,那么'll be used as the default parser, and it'将为您插入缺少的<body>
标记 . BeautifulSoup 3可能会把它留下来 .我强烈建议您删除后备,并坚持使用BeautifulSoup第4版 . 版本3已在几年前停止使用,并包含未修复的错误 . BeautifulSoup 4还提供了您可能想要使用的其他功能 .
BeautifulSoup是纯Python,可以在Python支持的任何平台上轻松安装到虚拟环境中 . 您在这里与系统提供的包绑定了.1336754_ .
以Debian Squeezy为例,你会遇到BeautifulSoup 3.1.0,甚至是BeautifulSoup developers do not want you to use it! . 您对
findAll
的问题几乎肯定源于使用该版本 .