How can I access the developer console in python using requests? - python

I am creating a script that logs onto Discord by using a token.
This is my code:
import requests
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
with requests.Session() as s:
url = 'https://discord.com/login'
r = s.get(url, headers=headers)
print(r.content)
In order to actually login using a token I need to run the following code in the browser's developer console:
function login(token) {
setInterval(() => {
document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`
}, 50);
setTimeout(() => {
location.reload();
}, 2500);
}
login ("[enter your token here]")
I know that this is possible in selenium but I really need to do it in requests.

Related

Python POST works only if I GET CSRF token before I POST, why?

I have the following code:
def main():
session_requests = requests.session()
result = session_requests.get(login_url)
tree = html.fromstring(result.text)
veri_token = tree.xpath("/html/body/div[1]/div/div/form/input[1]/#value")[0]
print(veri_token)
headerpayload = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'Host': host,
'Origin': origin,
'Referer': login_url,
'__RequestVerificationToken': veri_token
}
payload = {
"__RequestVerificationToken": veri_token,
"Q_b9849eb2-813d-4d0a-a1ce-643f1c8af986_0": "name",
"Q_62ebd8c8-7d45-481d-a8b1-ad54a390a029_0": "name#utoronto.ca",
"FormId": "276caa59-80a5-4ced-9b9d-025e1d753b4a",
"_ACTION": "Continue",
"PageIndex": "1"
}
result = session_requests.post(
login_url,
data=payload,
headers=headerpayload
)
print(result.status_code)
If I run this code everything works fine. But if I make the script print out the token and then just specify the token rather than get it before sending the post, it fails with a CSRF error. Any idea why?
EDIT: Just to clarify, I have to run both the get request and post together for this to work, if I separate them into two scripts and manually enter the veri_token it fails.

Why does 2captcha not resolve recaptcha?

So basically I'm trying to make an program that automates creating accounts for this specific websites that needs captcha when creating an account. I'm trying to get a token from 2captcha (captcha token provider) which i then store in "g-recaptcha-response", but when i run the program im still stuck on the captcha site and it asks for captcha.
import requests
from time import sleep
api_key = "API-KEY"
site_key = "SITE-KEy"
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
}
url = "https://www.nakedcph.com/en/auth/view?op=register"
with requests.Session() as s:
captcha_id = s.post("http://2captcha.com/in.php?key={}&method=userrecaptcha&invisible=1&googlekey={}&pageurl={}".format(api_key, site_key, url)).text.split('|')[1]
recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(api_key, captcha_id)).text
print("solving captcha...")
while "CAPCHA_NOT_READY" in recaptcha_answer:
sleep(5)
recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(api_key, captcha_id)).text
recaptcha_answer = recaptcha_answer.split('|')[1]
print(recaptcha_answer)
data = {
"firstName": "example",
"email": "example",
"password": "example",
"termsAccepted": "true",
"g-recaptcha-response": recaptcha_answer
}
r = s.post(url, data=data, headers=headers)
print(r.status_code)
Your problem is not in the captcha.
When you register an account, the request is sent to /auth/submit but you send the data to /auth/view?op=register
Your request does not contain proper headers
3._AntiCsrfToken is missing in your post data

How do you grab tokens in request headers using python requests

In the request headers when logging in, there's a header called "cookie" that changes every time, how would I grab that each time and put it in the headers using python requests?
screenshot of network tab in chrome
Heres my code:
import requests
import time
proxies = {
"http": "http://us.proxiware.com:2000"
}
login_data = {'op':'login-main', 'user':'UpbeatPark', 'passwd':'Testingreddit123', 'api_type':'json'}
comment_data = {'thing_id':'t3_gluktj', 'text':'epical. redditor', 'id':'#form-t3_gluktjbx2', 'r':'gaming','renderstyle':'html'}
s = requests.Session()
s.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4085.6 Safari/537.36'})
r = s.get('https://old.reddit.com/', proxies=proxies)
time.sleep(2)
r = s.post('https://old.reddit.com/api/login/UpbeatPark', proxies=proxies, data=login_data)
print(r.text)
here's the output (I know for a fact it is the correct password):
{"json": {"errors": [["WRONG_PASSWORD", "wrong password", "passwd"]]}}
This worked for me:
import requests
login_data = {
"op": "login-main",
"user": "USER",
"passwd": "PASS",
"api_type": "json",
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4085.6 Safari/537.36",
}
s = requests.Session()
r = s.post("https://old.reddit.com/api/login/USER", headers=headers, data=login_data)
print(r.text)
It seems exactly like the code you are using but without proxy. Can you try to turn it off? The proxy might block cookies.

Unable to succesfully add to cart via post request

I am emulating the requests sent to this website to try add a product to cart - although it is not working as intended and I am not sure why. Here is my series of requests sent.
s = requests.Session()
payload = {
"sku": "182418M20400102",
"serviceType": "product-details",
"userId": None,
}
headers = {
'content-type': 'application/json',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
s.get("https://www.ssense.com/en-ca/mini-shopping-bag") // Initialize cookies
resp = s.post("https://www.ssense.com/en-ca/api/shopping-bag/182418M20400102", json=payload, headers=headers)
print(resp.status_code)
bag = s.get("https://www.ssense.com/en-us/mini-shopping-bag")
print(bag.json())
Console printout is:
https://www.ssense.com/en-ca/api/shopping-bag/182418M20400102 // pid in this case
204 // Expected status code
{'quantity': 0, 'token': 'xxxx'} // qty should be 1
Not sure why it is not working.
you will have to do cookie management. this website stores your value in a cookie.
since you are making a post request, the next time you hit a get request, the values are stored in a cookie in the actual website. The web browsers manage our cookies so the bag has the data added. If you hit the same in incognito mode you will not have any data.
refer http://docs.python-requests.org/en/master/user/advanced/ for setting a cookie.

Python requests post received a wrong redirect URL

I'm trying to log in the web of our dean. But I received an error when posting data via Python Requests. After checking the process with Chrome, I found that the Method POST received an URL different from the one received on Chrome.
Here are parts of my codes.
import requests
url_get = 'http://ssfw.xjtu.edu.cn/index.portal'
url_post = 'https://cas.xjtu.edu.cn/login?service=http%3A%2F%2Fssfw.xjtu.edu.cn%2Findex.portal'
s = requests.session()
user = {"username": email,
"password": password,
}
header = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.8',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'141',
'Content-Type':'application/x-www-form-urlencoded',
'Host':'cas.xjtu.edu.cn',
'Origin':'https://cas.xjtu.edu.cn',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36'
}
I got the cookies from via a = s.get(url_get) and it should redirect to url_post, then add the cookie and referer.
_cookie = a.cookies['JSESSIONID']
header['Cookie'] = 'JSESSIONID='+_cookie
header['Referer']= 'https://cas.xjtu.edu.cn/login;jsessionid='+_cookie+'?service=http%3A%2F%2Fssfw.xjtu.edu.cn%2Findex.portal'
r = s.post(url2, json = user, allow_redirects = False)
But the r.headers['location'] == 'https://cas.xjtu.edu.cn/login?service=http%3A%2F%2Fssfw.xjtu.edu.cn%2Findex.portal'
On Chrome it should be http://ssfw.xjtu.edu.cn/index.portal?ticket=ST-211860-UEh41PdZXfpg4rsvyDg1-gdscas01
Hmm...Actually I wonder why they are different and how can I jump into the correct URL via Python Requests (Seems that the one on Chrome is correct)

Categories