【问题标题】:Python: ImportError: No module named 'HTMLParser' [duplicate]Python:ImportError:没有名为“HTMLParser”的模块[重复]
【发布时间】:2016-01-06 10:20:20
【问题描述】:

我是 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()

我收到以下错误:

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'

【问题讨论】:

标签: python-3.x


【解决方案1】:

该模块在 Python 3 中称为 html.parser。因此您需要更改导入以反映该新名称:

from html.parser import HTMLParser

您应始终检查standard library documentation 以确保您从正确的位置导入正确的内容。

【讨论】:

  • 谢谢,它似乎克服了这个问题。但是,我现在收到以下消息:
  • Traceback(最近一次调用最后):文件“C:\Users\bm250199\workspace\test\htmlparsing.py”,第 26 行,在 main() 文件“C:\Users \bm250199\workspace\test\htmlparsing.py",第 22 行,在主要 parser.feed() 类型错误:feed() 缺少 1 个必需的位置参数:'data'
  • 再次,check the documentation 并阅读错误消息:您需要将数据传递给 parser.feed()
  • 向 parser.feed 添加数据时工作正常。谢谢
  • 从 3.5 开始更新,您将收到一个弃用警告:The unescape method is deprecated and will be removed in 3.5, use html.unescape() instead. 现在只是 from html import unescapeescaped_text = unescape(original_text)
猜你喜欢
  • 2014-04-04
  • 2011-02-01
  • 2020-02-18
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
相关资源
最近更新 更多