How to “log in” to a website using Python's Requests module?

前端 未结 6 1874
别那么骄傲
别那么骄傲 2020-11-22 02:48

I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I\'m new to this...so I can\'t figure out if I should ma

6条回答
  •  感动是毒
    2020-11-22 03:22

    The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

    import requests
    from bs4 import BeautifulSoup
    
    payload = {
        'email': 'email@example.com',
        'password': 'passw0rd'
    }     
    
    with requests.Session() as sess:
        res = sess.get(server_name + '/signin')
        signin = BeautifulSoup(res._content, 'html.parser')
        payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
        res = sess.post(server_name + '/auth/login', data=payload)
    

提交回复
热议问题