2015-04-04 161 views
0

我正在嘗試爲網站設置Cookie,但是如果我打印CookieList,則只會獲取由網站設置的會話ID Cookie,而不是我嘗試設置的Cookie。設置服務器Cookie

我試圖按照文檔,但無法弄清楚爲什麼它不起作用。

親切的問候, 馬克

import requests 
from bs4 import BeautifulSoup 

s = requests.session() 
cookie = {"testcookie":"testvalue"} 
header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36)"} 
s.get("http://www.example.com", cookies=cookie, headers=header) 

# Get xsrf code 
loginpage = s.get("https://example.com/login/", headers=header) 
soup = BeautifulSoup(loginpage.text) 
xsrflist = [] 
source=soup.findAll('input',{"value":True}) 
for sources in source: 
    print (sources['value']) 
    xsrflist.append(sources["value"]) 
xsrf = xsrflist[0] 

# Login 
payload = {"username" : "usernamel", "password" : "password1", 'anti_xsrf_token' : xsrf} 
login = s.post("https://example.com/login/", data=payload, cookies=cookie, headers=header) 

print(s.headers) 
print (requests.utils.dict_from_cookiejar(s.cookies)) 
+0

你可以使用[selenium](https://selenium-python.readthedocs.org/),所以你不需要維護會話,然後做什麼想做的事情。 – 2015-04-04 17:17:28

+0

謝謝你的回答,你能詳細解釋一下嗎?我知道硒,但在這種特殊情況下硒會提供什麼改進而不是要求? – Martei 2015-04-04 17:28:58

回答

2

你不能設置一個服務器cookie。當你發送cookie到服務器時,服務器可以做任何事情,包括忽略它們。

+0

謝謝你的回答,這使得它更加清晰。所以我不應該發送服務器的cookie,因爲cookie的目的是信息。因此,如果例如cookie中存在會話ID,我應該找到正在請求會話ID的位置並使用該ID,而不是嘗試使用cookie。 – Martei 2015-04-04 17:25:03

0

要安裝硒

pip install selenium 

這裏是解決方案。

from selenium import webdriver 

driver = webdriver.Firefox() 
driver.get('yoururl') 
htmlpage = driver.page_source 
#do something with htmlpage