简体   繁体   中英

How can i login to website with python requests?

I would like to login to a website using python requests, the site in question is: https://www.subito.it/

Also I would like to know how to confirm that the program is able to login.

This is my code:

import requests

def login(email, password):
    response = requests.get('https://www.subito.it/')
    s = requests.session()
    payload = {
        'username': email, 
        'password': password, 
        'remember_me': "true", 
        'back': ""
    }
    
    response = s.post('https://areariservata.subito.it/hera-api/login', json=payload)
    
    print(response.content)
    print("Status code: ", response.status_code)
    if response.ok:
        print("All good!") 
    else:
        print("Something went wrong...")

session = login('MY_EMAIL', 'MY_PASSWORD')

As I was saying... you were on the right track by using "session" as it will take care of the cookies and you've correctly replicated the payload that the site is sending when it makes the call.
I think that you might missing be some headers... take a look at the "Request Headers" on the request done in the browser “”

One of the most important ones would be accept: application/json , most of the times is needed to have a correct JSON communication. If that's not enough... start adding the other ones 1 by 1 until you get what you want... or start with all of them and start eliminating them until you're left with the bare minimum. It might also be a good idea to copy the user-agent: ... in order to try to hide that you are using a script.

In the code all you'd have to do is something along these lines:

def login(email, password):
    ...
    headers = {
        "accept": "application/json",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
        # ... eventually other headers
    }
    res = s.post('https://areariservata.subito.it/hera-api/login', json=payload, headers=headers)
    # ... the rest of the code
    
    return s # you initially forgot this one

On a side note... I'd use a temporary/disposable account, until you get a satisfying/working script, in order to avoid getting a "ban" for too many login attempts. In case you get your IP banned, usually a restart of your router should change your public IP so it should be enough.

For the confirmation of the login response.status_code == 200 should be enough... my attempt with random input got me a 401.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM