我正在尝试获取csrftoken时收到错误 我尝试将令牌名称从csrftoken更改为csrf,但我仍然收到错误。
import requests
url='myurl'
Username='username'
Password='password'
requests.Session().get(url)
csrftoken= requests.Session().cookies['csrftoken']
logindata=dict(csrfmiddlewaretoken=csrftoken,username=
Username,password=Password)
requests.Session().post(url,data=logindata,headers={'referer' :'homepage'})
page=requests.session().get('2nd url')
print page.content
错误是: -
文件 “C:\用户\ DELL \应用程序数据\本地\程序\ Python的\ Python36-32 \ LIB \站点帕茨卡 es \ requests \ cookies.py“,第329行,在__getitem__return中 self._find_no_duplicates(名)'
文件 “C:\用户\ DELL \应用程序数据\本地\程序\ Python的\ Python36-32 \ LIB \站点帕茨卡 es \ requests \ cookies.py“,第400行,在_find_no_duplicates中加注 KeyError('name =%r,domain =%r,path =%r'%(name,domain,path)) eyError:“name ='csrftoken',domain = None,path = None”'
答案 0 :(得分:0)
此代码以资本" S"回避Session
版本的requests
部分。试着看看这是否适合你:
import requests
url = 'url'
client = requests.session()
# Retrieve the CSRF token first
csrf = client.get(url).cookies['csrftoken']
login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrf, next='/')
r = client.post(URL, data=login_data, headers=dict(Referer=url))
# Check if it worked?
print r.status_code
也许它在您安装时出现了问题?
<强> EDIT1:强>
试试这个:
import requests
from bs4 import BeautifulSoup
client = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0'}
url = 'url'
soup = BeautifulSoup(client.get(url).text, "html.parser")
csrf = soup.find(name="csrf")