登录到python请求失败的网站

2024-04-26 12:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试访问https://instacart.com/store/wegmans/storefront进行web抓取,但是当我尝试使用以下代码使用Python的请求登录时:

from requests import session
url = 'https://www.instacart.com'
payload = {
    'action': 'submit',
    'email': 'my_email@gmail.com',
    'password': 'my_password'
}

with session() as c:
    c.post(url, data=payload)
    response = c.get('https://instacart.com/store/wegmans/storefront')
    print(response.headers)
    print(response.text)

我会说“非常抱歉”回复.text,如下所示:响应.标题地址:

{'Date': 'Tue, 02 Jul 2019 02:58:57 GMT', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Server': 'nginx', 'Set-Cookie': 'build_sha=8f3eb623f91516ad5369c4c373e577ec406c0fa1;Path=/;', 'Cache-Control': 'no-cache', 'X-Request-Id': 'a13241fe-fdce-4eb5-bfa2-958118c7690c', 'X-Runtime': '0.007429', 'Vary': 'Origin'}

我不知道这是什么意思,但我猜“非常抱歉”是当它无法识别您的POST请求时的自动响应。当我手动登录时,密码和电子邮件就起作用了,我假设'action':'submit'部分是正确的,因为检查登录按钮会显示它的type=“submit”。你知道吗

我想知道这和instacart.com网站没有指向登录页的url。主页上有一个登录表单,但是你必须点击“已经有帐户了吗?”?在它弹出之前登录。这是问题所在还是我的代码有问题?你知道吗


Tags: store代码httpscomurlemailresponsesession
1条回答
网友
1楼 · 发布于 2024-04-26 12:29:23

这似乎适用于登录:

import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}

session = requests.Session()

res1 = session.get('http://www.instacart.com', headers=headers)
soup = BeautifulSoup(res1.content, 'html.parser')
token = soup.find('meta', {'name': 'csrf-token'}).get('content')
data = {"user": {"email": "your_email", "password": "your_password"},
        "authenticity_token": token}
res2 = session.post('https://www.instacart.com/accounts/login', headers=headers, data=data)
print(res2)
res3 = session.get('https://instacart.com/store/wegmans/storefront', headers=headers)
print(res3)
session.close()

正如@andreilozhkin评论的那样,从Chrome DevTools中,您可以确切地看到传递给POST请求的负载,其中包括“authenticity\u token”。我首先向http://www.instacart.com发出GET请求,并在PUT登录请求中使用该令牌。你知道吗

希望这有帮助。你知道吗

相关问题 更多 >