from urllib import request
from http import cookiejar
if __name__ == '__main__':
# 声明一个 CookieJar 对象实例来保存 cookie
cookie = cookiejar.CookieJar()
# 利用 urllib.request 库的 HTTPCookieProcessor 对象来创建 cookie 处理器,也就 CookieHandler
handler = request.HTTPCookieProcessor(cookie)
# 通过 CookieHandler 创建 opener
opener = request.build_opener(handler)
# 此处的 open 方法打开网页
response = opener.open('https://www.v2ex.com/')
# 打印 cookie 信息
for item in cookie:
print('Name = %s' % item.name)
print('Value = %s' % item.value)
2 个疑问:
一、利用上面的代码抓出的 cookie 可以是浏览器的中保存的吗?
二、利用这种方法我在抓某个站的时候提示
raise RemoteDisconnected("Remote end closed connection without" http.client.RemoteDisconnected: Remote end closed connection without response
通过搜索引擎得知是服务器限制了爬虫,所以有没有什么办法伪造 User-Agent。我知道 request 的请求头可以伪
造但是这个 CookieJar 的有些不理解。
请各位大牛协助解决下问题,非常感谢