python3 带着cookie读取网页源代码

大家可以参考这个博主的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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值