python3运行脚本出错:
import urllib2
def getHtml(url,headers):
req = urllib2.Request(url,headers=headers)
page = urllib2.urlopen(req)
html = page.read()
return html
报错:
原因:在sublimeText3中运行脚本,就会提示ImportError: No module named ‘urllib2′ ,这是因为SublimeText3内置了Python版本是3,已经不支持urllib2,需要改为以下命令:import urllib
修改了之后:
import urllib
def getHtml(url,headers):
req = urllib.Request(url,headers=headers)
page = urllib.urlopen(req)
html = page.read()
return html
又报错:
查了一些资料,真正原因是在Python3.X中改用了urllib.request。所以引用包需要更改为:import urllib.request
修改上述代码,重新运行即可。