Python Beautiful Soup'NonType'对象错误

时间:2014-04-16 15:27:59

标签: python html beautifulsoup findall

我正在使用Beautiful Soup来获取网页正文中的超链接。这是我使用的代码

import urllib2
from bs4 import BeautifulSoup

url = 'http://www.1914-1918.net/swb.htm'
element = 'body'
request = urllib2.Request(url)
page = urllib2.urlopen(request).read()
pageSoup = BeautifulSoup(page)
for elementSoup in pageSoup.find_all(element):
  for linkSoup in elementSoup.find_all('a'):
    print linkSoup['href']

当我尝试查找swb.htm页面的超链接时,我收到了一个AttributeError。

AttributeError:' NoneType'对象没有属性' next_element'

我确信有一个身体元素和几个' a'身体元素下的元素。但奇怪的是,它适用于其他页面(例如http://www.1914-1918.net/1div.htm)。

这个问题困扰了我好几天。任何人都可以指出我做错了什么。

截图

enter image description here

3 个答案:

答案 0 :(得分:3)

您的打印错误。 它应该是:

import urllib2
from bs4 import BeautifulSoup

url = 'http://www.1914-1918.net/swb.htm'
element = 'body'
request = urllib2.Request(url)
page = urllib2.urlopen(request).read()
pageSoup = BeautifulSoup(page)
for elementSoup in pageSoup.find_all(element):
  for linkSoup in elementSoup.find_all('a'):
    print linkSoup['href']

对我来说,这会返回很多链接。

答案 1 :(得分:1)

如果安装了html5lib,就会发生这种情况。

尝试删除它并重新测试。

更多细节: https://bugs.launchpad.net/beautifulsoup/+bug/1184417

答案 2 :(得分:-1)

也许beautifulsoup4不适合您的Python,请尝试删除beautifulsoup4:pip uninstall beautifulsoup4,并安装旧版本:pip install beautifulsoup4==<version>,我使用版本4.1.3

相关问题