大家可以参考这个博主的https://blog.csdn.net/com_ma/article/details/77486384
python3中 urllib和urllib2合为一体,因此这里用的是urllib.request。
除此之外需要cookiejar,python2中是cookielib,python3中改为了http.cookiejar。
import urllib
import http.cookiejar
import ssl
# 关闭证书验证, 避免urllib SSLError
ssl._create_default_https_context = ssl._create_unverified_context
# 构建opener
cj = http.cookiejar.CookieJar()
# 创建请求求管理器opener,其中urllib.request.HTTPCookieProcessor(cj)是管理器
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
# 将opener设为全局
urllib.install_opener(opener)
#当使用opener及urllib.request访问网页时会存储cookie,同时也是带着cookie访问网页
# 利用opener带着cookie获取网页源代码,get请求
url = "xxxxxx"
request = urllib.request.Request(url)
response = opener.open(request)
print(response.read().decode())
cookiejar的简介和使用可以参考https://blog.csdn.net/mouday/article/details/81185200