python2和python3中的urllib
在Python3中包urllib2归入了urllib中,所以要导入urllib.request,并且要把urllib2替换成urllib.request
# python2
import urllib2
url = 'http://www.jianshu.com/trending/weekly?page={}'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
request = urllib2.Request(url=url, headers=headers)
html = urllib2.urlopen(request)
print html.read()
# python3
import urllib.request
url = 'http://www.jianshu.com/trending/weekly?page={}'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
request = urllib.request.Request(url=url, headers=headers)
# urllib.request.urlopen(url,data,timeout) :第一个参数url,第二个参数是访问url要传送的数据,第三个参数是设置超时的时间
html= urllib.request.urlopen(request)
print(html.read())