在Python 3.x中BeautifulSoup4抛出错误
我正在尝试创建一个网页抓取工具,想用BeautifulSoup来实现。根据网站的说明,我安装了BeautifulSoup 4.3.2,因为它和python 3.x兼容。我使用了
pip install beautifulsoup4
来安装它。但是当我运行
from bs4 import BeautifulSoup
import requests
url = input("Enter a URL (start with www): ")
link = "http://" + url
data = requests.get(link).content
soup = BeautifulSoup(data)
for link in soup.find_all('a'):
print(link.get('href'))
时,出现了一个错误,提示是
Traceback (most recent call last):
File "/Users/user/Desktop/project.py", line 1, in <module>
from bs4 import BeautifulSoup
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages /bs4/__init__.py", line 30, in <module>
from .builder import builder_registry, ParserRejectedMarkup
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages/bs4/builder /__init__.py", line 308, in <module>
from .. import _htmlparser
ImportError: cannot import name _htmlparser
相关问题:
3 个回答
0
我刚刚修改了 bs4/builder/_htmlparser.py 文件,做了以下两点:
A) 没有导入 HTMLParseError 这个东西
from html.parser import HTMLParser
B) 定义了一个 HTMLParseError 类
class HTMLParseError(Exception):
"""Exception raised for all parse errors."""
def __init__(self, msg, position=(None, None)):
assert msg
self.msg = msg
self.lineno = position[0]
self.offset = position[1]
def __str__(self):
result = self.msg
if self.lineno is not None:
result = result + ", at line %d" % self.lineno
if self.offset is not None:
result = result + ", column %d" % (self.offset + 1)
return result
这样做可能不是最好的选择,因为 HTMLParserError 这个错误不会被抛出。不过!你的异常会被忽略,也就是没有处理。
1
我觉得源文件里可能有个错误,特别是在这里:
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages/bs4/builder /__init__.py", line 308, in <module>
from .. import _htmlparser
在我的安装中,bs4/builder/__init__.py的第308行
from . import _htmlparser
你可以试着直接在那修复一下,看看bs4能否成功导入。我不确定你安装的是哪个版本的bs4,但我的是4.3.2版本,_htmlparser.py也在bs4/builder里。
1
我刚在我的电脑上安装了Python 3.x,并测试了最新下载的BS4(Beautiful Soup 4)。结果没成功。不过,有个解决办法可以在这里找到:https://github.com/il-vladislav/BeautifulSoup4(感谢GitHub用户Il Vladislav,不知道你是谁)。
你可以下载这个压缩包,把里面的bs4文件夹覆盖到你下载的BeautifulSoup文件夹里,然后通过python setup.py install重新安装。现在在我这边可以正常工作了,下面的截图显示了在完全正常工作之前出现的错误。
代码:
from bs4 import BeautifulSoup
import requests
url = input("Enter a URL (start with www): ")
link = "http://" + url
data = requests.get(link).content
soup = BeautifulSoup(data)
for link in soup.find_all('a'):
print(link.get('href'))
截图:

相关的StackOverflow话题可以在这里找到,显示BS4目前还不是和Python 3.x完全兼容(即使已经过了两年)。