我想用 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/