我是Python的新手.我试图运行此代码,但我收到ImportError的错误消息:没有名为'HTMLParser'的模块.我使用的是Python 3.x. 有什么理由不行吗?
#Import the HTMLParser model
from HTMLParser import HTMLParser
#Create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
#Function to handle the processing of HTML comments
def handle_comment(self,data):
print ("Encountered comment: ", data)
pos = self.getpos()
print ("At line: ", pos[0], "position ", pos[1])
def main():
#Instantiate the parser and feed it some html
parser= MyHTMLParser()
#Open the sample file and read it
f = open("myhtml.html")
if f.mode== "r":
contents= f.read() #read the entire FileExistsError
parser.feed()
if __name__== "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "C:\Users\bm250199\workspace\test\htmlparsing.py", line 3, in <module>
from HTMLParser import HTMLParser
ImportError: No module named 'HTMLParser'
Run Code Online (Sandbox Code Playgroud)
pok*_*oke 50
该模块html.parser在Python 3中调用.因此您需要更改导入以反映该新名称:
from html.parser import HTMLParser
Run Code Online (Sandbox Code Playgroud)
您应该始终检查标准库文档,以确保从正确的位置导入正确的东西.
| 归档时间: |
|
| 查看次数: |
28790 次 |
| 最近记录: |