导入 httplib 导入错误:没有名为 httplib 的模块

2024-01-30

运行 test.py 时出现此错误

C:\Python32>python.exe test.py
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    import httplib
ImportError: No module named httplib

如何纠正呢?

代码块为test.py:

#!/usr/local/bin/python

import httplib
import sys
import re
from HTMLParser import HTMLParser


class miniHTMLParser( HTMLParser ):

  viewedQueue = []
  instQueue = []

  def get_next_link( self ):
    if self.instQueue == []:
      return ''
    else:
      return self.instQueue.pop(0)


  def gethtmlfile( self, site, page ):
    try:
      httpconn = httplib.HTTPConnection(site)
      httpconn.request("GET", page)
      resp = httpconn.getresponse()
      resppage = resp.read()
    except:
      resppage = ""

    return resppage


  def handle_starttag( self, tag, attrs ):
    if tag == 'a':
      newstr = str(attrs[0][1])
      if re.search('http', newstr) == None:
        if re.search('mailto', newstr) == None:
          if re.search('htm', newstr) != None:
            if (newstr in self.viewedQueue) == False:
              print ("  adding", newstr)
              self.instQueue.append( newstr )
              self.viewedQueue.append( newstr )
          else:
            print ("  ignoring", newstr)
        else:
          print ("  ignoring", newstr)
      else:
        print ("  ignoring", newstr)


def main():

  if sys.argv[1] == '':
    print ("usage is ./minispider.py site link")
    sys.exit(2)

  mySpider = miniHTMLParser()

  link = sys.argv[2]

  while link != '':

    print ("\nChecking link ", link)

    # Get the file from the site and link
    retfile = mySpider.gethtmlfile( sys.argv[1], link )

    # Feed the file into the HTML parser
    mySpider.feed(retfile)

    # Search the retfile here

    # Get the next link in level traversal order
    link = mySpider.get_next_link()

  mySpider.close()

  print ("\ndone\n")

if __name__ == "__main__":
  main()

您正在 Python 3 上运行 Python 2 代码。在 Python 3 中,该模块已重命名为http.client http://docs.python.org/3/library/http.client.html.

你可以尝试运行2to3 tool http://docs.python.org/2/library/2to3.html#to3-reference在您的代码上,并尝试自动翻译它。参考文献httplib将自动重写以使用http.client反而。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

导入 httplib 导入错误:没有名为 httplib 的模块 的相关文章

随机推荐