我的python 3.4.4代码是:
import urllib.request
from bs4 import BeautifulSoup
from html.parser import HTMLParser
urls = 'file:///C:/Users/tarunuday/Documents/scrapdata/mech.html'
htmlfile = urllib.request.urlopen(urls)
soup = BeautifulSoup(htmlfile,html.parser)
我收到此错误
Traceback (most recent call last):
File "C:\Python34\saved\scrapping\scrapping2.py", line 7, in <module>
soup = BeautifulSoup(htmlfile,html.parser)
NameError: name 'html' is not defined
现在我明白HTMLParser是py2.x而html.parser是py3.x但我怎么能让它工作? bs4 site说If you get the ImportError “No module named html.parser”, your problem is that you’re running the Python 3 version of the code under Python 2.
,但我运行的是3.x而且我得到的是NameError而不是ImportError
答案 0 :(得分:3)
错误是正确的,您还没有在任何地方定义html
。您链接的文档显示您应该将"html.parser"
作为字符串传递;它看起来根本不需要导入HTMLParser。
答案 1 :(得分:0)
在您的代码html.parser
中是一个字符串,如果您使用的是python 3或更高版本,则需要在其周围加上引号。