使用Python requests登录网站

4

我正在尝试使用Python 3、Requests和lxml登录一个网页。但是,在向登录页面发送post请求后,我无法进入登录后可用的页面。我错过了什么吗?

import requests
from lxml import html

session_requests = requests.session()

login_URL = 'https://www.voetbal.nl/inloggen'
r = session_requests.get(login_URL)

tree = html.fromstring(r.text)
form_build_id = list(set(tree.xpath("//input[@name='form_build_id']/@value")))[0]

payload = {
    'email':'mom.soccer@mail.com',
    'password':'testaccount',
    'form_build_id':form_build_id
    }

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding':'gzip, deflate, br',
    'Accept-Language':'nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cache-Control':'max-age=0',
    'Connection':'keep-alive',
    'Content-Type':'multipart/form-data; boundary=----WebKitFormBoundarymGk1EraI6yqTHktz',
    'Host':'www.voetbal.nl',
    'Origin':'https://www.voetbal.nl',
    'Referer':'https://www.voetbal.nl/inloggen',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }

result = session_requests.post(
    login_URL,
    data = payload,
    headers = headers
)

pvc_url = 'https://www.voetbal.nl/club/BBCB10Z/overzicht'
result_pvc = session_requests.get(
    pvc_url,
    headers = headers
)

print(result_pvc.text)

这个示例中的账号已经激活,但只是我创建来提出问题的测试账号。请随意尝试。

2
我怀疑登录成功会返回一个 cookie,你需要将其存储并在每个随后的页面中呈现。请查看 http://docs.python-requests.org/en/master/user/quickstart/#cookies - match
作为上述内容的后续,尝试在您最后的get请求中添加cookies=result.cookies。 - Pathead
1
实际上,您不必使用“files”,只需将此 'form_id': 'voetbal_login_login_form' 添加到 payload 中即可。 - t.m.adam
另外,我在头部中放置了一个Content-Type(WebKitFormBoundary,后跟随机字符串)。这个WebKitFormBoundary后跟随机字符串也出现在有效载荷中,但是该字符串似乎是动态的。这可能是问题所在吗?我在哪里可以找到动态部分? - Iglias67
您不需要任何头文件,也不必手动设置cookie - 这样做会使您的问题失去意义。只需更改有效载荷,您就应该能够登录。 - t.m.adam
显示剩余3条评论
1个回答

1

答案:

存在多个问题:

有效负载:缺少“form_id”:“voetbal_login_login_form”。感谢@t.m.adam

Cookies:请求Cookie丢失。它们似乎是静态的,所以我尝试手动添加它们,这起作用了。感谢@match和@Patrick Doyle

标头:删除了包含动态部分的“content-type”行。

现在登录非常顺利!


1
你能否贴出需要更改的代码来修复问题,而不仅仅是描述修复方法呢? - Adam Barnes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接