1

I'm trying to login to twitter using just requests but I don't think I'm building the correct login response. I pass in the guest token but am I missing anything else? Am I using the correct URL? What am I doing wrong? And also how would I tell if I successfully login this way - with my current iteration I get a 200 status code but I'm 100% sure it's not from me successfully logging in.

import requests

headers = {
    'accept': '*/*',
    'authorization': public_bearer,
    'content-type': 'application/json',
    'referer': 'https://twitter.com/',
    'user-agent': user_agent,
    'x-guest-token': guest_token
}

data = {
    'username': username,
    'password': password
}

r = requests.post('https://twitter.com/login', headers=headers, data=data)
print(r.status_code)
print(r.headers)

edit: the question is more along the lines of how the request flow is supposed to be built

hwhat
  • 326
  • 1
  • 5
  • 14
  • A crude way to determine whether the login was successful is to compare the content you receive when you use incorrect and correct credentials. – Übermensch Apr 06 '23 at 01:08
  • I currently don't know the exact request flow that allows one to go from the login page to the home page, but this definitely sounds like something that requests' [Session class](https://requests.readthedocs.io/en/latest/user/advanced/) could solve. This person's [answer](https://stackoverflow.com/a/17633072/13684789) to a similar question might also be helpful. – Übermensch Apr 06 '23 at 13:19

1 Answers1

0

If you wanted to know whether it was successfully login, you eventually can validate based on the status code or response body (like the headers or so on). The simplest way to do is just like :

r = requests.post('https://twitter.com/login', headers=headers, data=data)
if r.status_code == 200:
   print("Successfully login to Twitter")
else:
   print(f"Unable login to Twitter, status code is :{r.status_code}")
  • the problem is that the code i provided gives me a 200 but i'm not logged in. i see no csrf token in the response. edit: the question is more along the lines of, what am i doing wrong and what is the request i need to make to login successfully – hwhat Apr 05 '23 at 04:31
  • do you intend to do web scraping or use the Twitter API? if you fully intend to do the web scraping, then you need to parsing the HTML content using `bs4` library to extract the necessary input fields and values for the login data – ryaneatdinosaurs Apr 05 '23 at 05:52
  • 1
    webscraping. i don't need bs4 to do this... – hwhat Apr 05 '23 at 06:06