簡體   English   中英

Python請求中的空RequestsCookieJar

[英]Empty RequestsCookieJar in Python requests

我正在使用Python請求模塊。

>>> import requests
>>> s1 = requests.Session()
>>> r1 = s1.get("https://www.facebook.com/")
>>> r1.cookies
<RequestsCookieJar[Cookie(version=0, name='fr', ... ]>

RequestsCookieJar已滿,並且我嘗試的每個URL都已滿。 但是對於Instagram,我得到:

>>> s2 = requests.Session()
>>> r2 = s2.get("https://www.instagram.com/")
>>> r2.cookies
<RequestsCookieJar[]>

RequestsCookieJar為空,但它應該返回一些內容。

有人可以解釋一下為什么會這樣嗎?

謝謝。

這是因為Instagram的。 當您首先打開instagram時,它不會向您發送cookie,您必須登錄或再次提出獲取請求。

更新:當您要登錄並想要csrf令牌時,有以下方法:

import json
import requests
import lxml.html

def get_csrf_token(content):
    xpath_data = lxml.html.fromstring(content).xpath('/html/body/script[1]/text()')[0]
    raw_json = xpath_data[xpath_data.find('{'):-1]
    return json.loads(raw_json)["config"]["csrf_token"]

def get_main_page():
    session = requests.Session()
    content = session.get('https://instagram.com')

    csrf_token = get_csrf_token(content.content)
    header = {'x-csrftoken'      : csrf_token,
              'x-requested-with' : 'XMLHttpRequest',
              'User-Agent'       : "Your user agent there",
              "referer"          : 'https://instagram.com',
              "cookie"           : "ig_cb=1",
              "origin"           : 'https://instagram.com'}

    session.headers.update(header)

我假設您可以編寫“ POST”方法來通過登錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM