Python Beautiful Soup’NonType’对象错误

我正在使用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’

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

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

截图

解决方法:

你的打印错了.
它应该是:

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']

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

上一篇:Python -- re模块


下一篇:(转)CrudRepository JpaRepository PagingAndSortingRepository之间的区别