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

前端 未结 6 1529
别那么骄傲
别那么骄傲 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:06

    I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:

    Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.

    Once you've got that, you can use a requests.Session() instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.

    Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.

    Example

    import requests
    
    # Fill in your details here to be posted to the login form.
    payload = {
        'inUserName': 'username',
        'inUserPass': 'password'
    }
    
    # Use 'with' to ensure the session context is closed after use.
    with requests.Session() as s:
        p = s.post('LOGIN_URL', data=payload)
        # print the html returned or something more intelligent to see if it's a successful login page.
        print p.text
    
        # An authorised request.
        r = s.get('A protected web page url')
        print r.text
            # etc...
    

提交回复
热议问题