Python 导入 httplib 导入错误:没有名为 httplib 的模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13778252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
import httplib ImportError: No module named httplib
提问by Elshan
I got this error when run test.py
运行 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
How to correct it?
如何纠正?
Code block for test.py:
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()
采纳答案by Martijn Pieters
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.
您正在 Python 3 上运行 Python 2 代码。在 Python 3 中,模块已重命名为http.client.
You could try to run the 2to3toolon your code, and try to have it translated automatically. References to httplibwill automatically be rewritten to use http.clientinstead.
您可以尝试在您的代码上运行该2to3工具,并尝试使其自动翻译。对的引用httplib将被自动重写以http.client代替使用。
回答by Ryan Shillington
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
当我试图让我的 Docker 容器更小时,我遇到了这个问题。这是因为我安装了 Python 2.7:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommendsflag:
而且我不应该包含--no-install-recommends标志:
apt-get install -y python


