Reputation: 461
I am using python requests to login to a website, but it will not accept my request.
I have looked for hidden inputs in the source code of the website but could not find any, and I have heard that it could be something to do with adding headers, but I don't know how to find the headers or how to add them to my code.
session = requests.session()
login_data = {
'csrfmiddlewaretoken': 'S75hu6eF1FV6axGK8ffV5JC7mYw8Z3AbviU453U0rOQPYPu7iiBCVxRnV2XywfVh',
'username': '<my_username>',
'password': '<my_password>',
'next': '/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms'
}
session.get(url)
r = session.post('https://www.memrise.com/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms/login.py', login_data)
if r.status_code == 200:
res = session.get(url)
print('YES!!!')
else:
print('NOOOOOOOOOOOOOOOO')
I would expect for the status code to be 200, but it is not- I don't know what the status code is when it doesn't accept the request. Any help would be appreciated in solving this problem.
Upvotes: 1
Views: 371
Reputation: 555
www.memrise.com has CSRF-Token method in it's login, so you have to find CSRF-Token from login page using BeautifulSoup and use headers.
import bs4
import requests
url = 'https://www.memrise.com/login/'
session = requests.session()
response = session.get(url)
soup = bs4.BeautifulSoup(response.text, 'lxml')
csrf_token = soup.find('input', {'name': 'csrfmiddlewaretoken'}).get('value')
headers = {
'Host': 'www.memrise.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.memrise.com/login/',
'Content-Type': 'application/x-www-form-urlencoded',
}
login_data = {
'csrfmiddlewaretoken': csrf_token,
'username': '<my_username>',
'password': '<my_password>',
'next': '/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms'
}
r = session.post(url, login_data, headers=headers)
if r.status_code == 200:
res = session.get(url)
print('YES!!!')
else:
print('NO')
Upvotes: 3