使用Python中的请求模块登录巴克莱高级联盟梦幻足球?

时间:2016-08-07 23:40:22

标签: python session login request

我正在尝试编写一个Python脚本,让我在https://fantasy.premierleague.com/登录我的幻想足球帐户,但登录时出现的情况不太正确。当我通过浏览器登录并查看详细信息时使用Chrome开发者工具,我发现请求网址为https://users.premierleague.com/accounts/login/,发送的表单数据为:

csrfmiddlewaretoken:[My token]
login:[My username]
password:[My password]
app:plfpl-web
redirect_uri:https://fantasy.premierleague.com/a/login

还有许多请求标头:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:185
Content-Type:application/x-www-form-urlencoded
Cookie:[My cookies]
Host:users.premierleague.com
Origin:https://fantasy.premierleague.com
Referer:https://fantasy.premierleague.com/
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

所以我使用请求库编写了一个简短的Python脚本,尝试登录并导航到页面,如下所示:

import requests
with requests.Session() as session:
url_home = 'https://fantasy.premierleague.com/'
html_home = session.get(url_home)
csrftoken = session.cookies['csrftoken']
values = {
    'csrfmiddlewaretoken': csrftoken,
    'login': <My username>,
    'password': <My password>,
    'app': 'plfpl-web',
    'redirect_uri': 'https://fantasy.premierleague.com/a/login'
}
head = {
    'Host':'users.premierleague.com',
    'Referer': 'https://fantasy.premierleague.com/',
}
session.post('https://users.premierleague.com/accounts/login/', 
             data = values, headers = head)
url_transfers = 'https://fantasy.premierleague.com/a/squad/transfers'
html_transfers = session.get(url_transfers)
print(html_transfers.content)

在打印出我的帖子请求的内容时,我收到了一个HTML响应代码500错误:

b'\n<html>\n<head>\n<title>Fastly error: unknown domain users.premierleague.com</title>\n</head>\n<body>\nFastly error: unknown domain: users.premierleague.com. Please check that this domain has been added to a service.</body></html>'  

如果我从头部字典中删除“主机”,则会收到HTML响应代码405错误:

b''

我尝试在头脑中包含各种请求标头组合,似乎没有任何效果。

1 个答案:

答案 0 :(得分:3)

以下对我有用。我只是删除了headers = head

session.post('https://users.premierleague.com/accounts/login/', 
             data = values)

我认为您正在尝试以编程方式选择您的团队,就像我一样。你的代码让我开始感谢。