1.python2
import urllib
import urllib2
共同点:都可以直接用urlopen(‘url’)请求页面
不同点:
urllib有urlencode(dict)和unquote()进行编码和解码
对于error:
try:
response = urllib2.urlopen("http://pythonsite.com/111341.html")
except urllib2.HTTPError as e:
print(e.reason)
print(e.code)
print(e.headers)
except urllib2.URLError as e:
print(e.reason)
else:
print("reqeust successfully")
2.python3
请求页面:urllib.request.urlopen(‘url’)
对于error:
from urllib import request,error try: response = request.urlopen("http://pythonsite.com/113211.html") except error.HTTPError as e: print(e.reason) print(e.code) print(e.headers) except error.URLError as e: print(e.reason) else: print("reqeust successfully")