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

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

    Find out the name of the inputs used on the websites form for usernames <...name=username.../> and passwords <...name=password../> and replace them in the script below. Also replace the URL to point at the desired site to log into.

    login.py

    #!/usr/bin/env python
    
    import requests
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    payload = { 'username': 'user@email.com', 'password': 'blahblahsecretpassw0rd' }
    url = 'https://website.com/login.html'
    requests.post(url, data=payload, verify=False)
    

    The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.

    Extra:

    To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

    # Custom scripts
    export CUSTOM_SCRIPTS=home/scripts
    export PATH=$CUSTOM_SCRIPTS:$PATH
    

    Then create a link to this python script inside home/scripts/login.py

    ln -s ~/home/scripts/login.py ~/home/scripts/login
    

    Close your terminal, start a new one, run login

提交回复
热议问题