Python靓汤“无名氏”obj

2024-05-19 07:07:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我用美丽的汤来获取网页正文的超链接。这是我使用的代码

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:“NoneType”对象没有属性“next_element”

我确信在body元素下有一个body元素和几个'a'元素。但奇怪的是,它在其他页面(例如http://www.1914-1918.net/1div.htm)上也能很好地工作。在

这个问题已经困扰我好几天了。谁能指出我做错了什么吗。在

截图

enter image description here


Tags: importhttpurl元素fornetrequestpage
3条回答

当安装了html5lib时会发生这种情况。在

只需尝试删除它,然后再次测试。在

更多详情: https://bugs.launchpad.net/beautifulsoup/+bug/1184417

你的指纹错了。 它应该是:

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

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

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

相关问题 更多 >

    热门问题