简体   繁体   中英

Issues with logging in using Python Requests

Note: I am doing this on a website which sole purpose is to be used for automation tests

import requests

Payload = {
    'username': 'test',
    'password': 'test'
}

p = requests.post('https://petstore.octoperf.com/actions/Account.action', data=Payload)

print(p.text)

The credentials in the Payload are the correct ones and when I look at what it prints, I do not see 'sign out' which I should see if it has successfully signed in.

ok you're missing a lot of info. your payload is incomplete, you're missing signon field and hidden fields _sourcePage and __fp . those are in the form you submit, so you'll have to make a GET request first to catch these values. you need also the jsessionid cookie, so a requests session should be useful

import requests
from bs4 import BeautifulSoup

payload = {
    'username': 'test',
    'password': 'test',
    'signon': 'Login'
}
url='https://petstore.octoperf.com/actions/Account.action'
# use a session to keep cookies alive
with requests.session() as s:
    
    # make a get first to scrape input values
    r = s.get(url)
    
    # grab inputs and add their values to the payload
    soup=BeautifulSoup(r.text, 'lxml')
    inputs=soup.select('form[action*="Account"] input[type="hidden"]')
    for inp in inputs:
        payload[inp.attrs['name']]=inp.attrs['value']
        
    # and connect finally with all data
    r = s.post(url, data=payload)
    soup=BeautifulSoup(r.text, 'lxml')
    print(soup.select_one('#WelcomeContent').text.strip())
    >>> Welcome test!

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