python - 使用 urllib 启用 cookie

标签 python cookies urllib

我想用 urllib python 库解析一个网站。我写了这个:

import urllib as web
source_rep.urlopen(url_rep).read()
print source_rep

该网站返回给我一条消息,说我应该启用 cookie。我怎样才能用 python 做到这一点?

最佳答案

此答案已使用 Python 3.7 进行测试。我通常会为我想要 cookie 的每个随机 URL 使用新的开启器

from urllib.request import build_opener, HTTPCookieProcessor, Request
url = 'https://www.cell.com/cell-metabolism/fulltext/S1550-4131(18)30630-2'
opener = build_opener(HTTPCookieProcessor())

没有 Request 对象:

response = opener.open(url, timeout=30)
content = response.read()

使用 Request 对象:

request = Request(url)
response = opener.open(request, timeout=30)
content = response.read()

关于python - 使用 urllib 启用 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29395407/

相关文章:

python - 使用 Python + lxml (xpath) 从网站抓取/提取文本并打印

python - Django 删除前导零

javascript - api请求成功后如何在express中设置cookie

Python 3 urllib urlparse URL解析

python - 如何将字符串转换为 BeautifulSoup 对象?

python - 为不同平台构建 python wheels

node.js - 检查 session 时无法读取未定义的属性 "name"

google-chrome - Chrome 80+ 与跨站点资源关联的 cookie 设置为没有 `SameSite` 属性。已被屏蔽

Python 3 urllib.request.urlopen

Python requests.get 和 urllib.urlopen 返回不同的 HTML 到浏览器