我正在使用 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 Beautiful Soup 'NoneType' 对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23113803/