Import httplib Import Error: 没有名为 httplib 的模块

在运行 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()
212010 次浏览

您在 Python3上运行 Python2代码,在 Python3中,模块被重命名为 http.client

您可以尝试在代码上运行 2to3工具,并尝试自动翻译它。对 httplib的引用将自动重写为使用 http.client

当我试图让我的 Docker 容器变小时,我遇到了这个问题。这是因为我在安装 Python 2.7时使用了:

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

而且我不应该把 --no-install-recommends的标志包括在内:

apt-get install -y python

如果您使用 PyCharm,请将您的“项目解释器”更改为“2.7. x”

enter image description here

您只需导入 http.client 并用以下代码将其重命名为 httplib:

将 http.client 导入为 httplib