76

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()
4

4 に答える 4

144

Python3でPython2コードを実行しています。Python3では、モジュールの名前がに変更されましたhttp.client

コードで2to3ツールを実行して、自動的に変換してみることができます。への参照は、代わりhttplibに使用するように自動的に書き直されますhttp.client

于 2012-12-08T14:16:21.627 に答える
3

次のコードを使用して、http.clientをインポートし、名前をhttplibに変更できます。

http.clientをhttplibとしてインポートします

于 2021-05-15T20:28:14.137 に答える
-1

PyCharmを使用する場合は、「ProjectInterpreter」を「2.7.x」に変更してください。

ここに画像の説明を入力してください

于 2019-12-30T12:58:35.410 に答える
-2

Dockerコンテナを小さくしようとしたときに、この問題が発生しました。これは、Python2.7を次のコマンドでインストールしたためです。

apt-get install -y --no-install-recommends python

そして、私は--no-install-recommends旗を含めるべきではありませんでした:

apt-get install -y python
于 2019-08-13T20:42:21.393 に答える