【问题标题】:not getting all cookie info using python requests module没有使用 python 请求模块获取所有 cookie 信息
【发布时间】:2015-07-07 20:17:02
【问题描述】:

我正在学习如何使用 python 请求模块登录示例网站。这 Video Tutorial 让我开始。从我在 GoogleChrome>Inspect Element>NetworkTab 中看到的所有 cookie 中,我无法使用以下代码检索所有这些 cookie:

import requests
with requests.Session() as s:
    url = 'http://www.noobmovies.com/accounts/login/?next=/'
    s.get(url)
    allcookies = s.cookies.get_dict()
    print allcookies

使用这个我只能得到如下的 csrftoken:

{'csrftoken': 'ePE8zGxV4yHJ5j1NoGbXnhLK1FQ4jwqO'}

但在 google chrome 中,我看到了除 csrftoken 之外的所有其他 cookie(sessionid、_gat、_ga 等):

我什至尝试了here的以下代码,但结果是一样的:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()
#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

#create a request object to be used to get the page.
req = Request("http://www.noobmovies.com/accounts/login/?next=/")
f = opener.open(req)

#see the first few lines of the page
html = f.read()
print html[:50]

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie

输出:

<!DOCTYPE html>
<html xmlns="http://www.w3.org
the cookies are: 
<Cookie csrftoken=ePE8zGxV4yHJ5j1NoGbXnhLK1FQ4jwqO for www.noobmovies.com/>

那么,我怎样才能得到所有的 cookie 呢?谢谢。

【问题讨论】:

  • 谷歌添加了这些请求cookies吗?您如何从响应中获取随请求发送的 cookie?
  • @dm03514,我不确定。我在 safari 浏览器(支持雅虎搜索)中检查了相同的内容,并返回了相同的 cookie 列表。你能详细说明你所说的第二部分吗?

标签: python cookies python-requests


【解决方案1】:

设置的 cookie 来自其他页面/资源,可能由 JavaScript 代码加载。您可以使用wgetcurlhttpie 等工具检查是否仅向页面发出请求(无需运行JS 代码)。

此服务器设置的唯一 cookie 是 csrftoken,如您所见:

$ wget --server-response 'http://www.noobmovies.com/accounts/login/?next=/'
--2016-02-01 22:51:55--  http://www.noobmovies.com/accounts/login/?next=/
Resolving www.noobmovies.com (www.noobmovies.com)... 69.164.217.90
Connecting to www.noobmovies.com (www.noobmovies.com)|69.164.217.90|:80... connected.
HTTP request sent, awaiting response... 
  HTTP/1.1 200 OK
  Server: nginx/1.4.6 (Ubuntu)
  Date: Tue, 02 Feb 2016 00:51:58 GMT
  Content-Type: text/html; charset=utf-8
  Transfer-Encoding: chunked
  Connection: keep-alive
  Vary: Accept-Encoding
  Expires: Tue, 02 Feb 2016 00:51:58 GMT
  Vary: Cookie,Accept-Encoding
  Cache-Control: max-age=0
  Set-Cookie: csrftoken=XJ07sWhMpT1hqv4K96lXkyDWAYIFt1W5; expires=Tue, 31-Jan-2017 00:51:58 GMT; Max-Age=31449600; Path=/
  Last-Modified: Tue, 02 Feb 2016 00:51:58 GMT
Length: unspecified [text/html]
Saving to: ‘index.html?next=%2F’

index.html?next=%2F             [      <=>                                   ]  10,83K  2,93KB/s    in 3,7s    

2016-02-01 22:52:03 (2,93 KB/s) - ‘index.html?next=%2F’ saved [11085]

注意Set-Cookie 这一行。

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多