Suppose you have a web app whose client is supposed to be something other than a web browser, such as a mobile app.
It doesn't have a login page like you would see in a typical web service. This is because the client app contains a login form.
However, when doing automatic testing, I want to access it from the Selenium browser and see how it works. At that time.
python
import requests
from selenium import webdriver
cookie_name = 'session_id'
#Log in with requests and make a session cookie
s = requests.session()
login_data = {
'email': '[email protected]',
'password': 'xxxxxxxxxx',
}
res = s.post('https://example.com/login/', data=login_data)
res.raise_for_status()
#Session cookie value
cookie_value = s.cookies.get(cookie_name)
#Firefox launch
driver = webdriver.Firefox()
#Open an appropriate page for the target domain in advance.
#If you don't do this, add_I get an error with a cookie
driver.get('https://example.com/')
#Pass the session cookie obtained by requests to Firefox
driver.add_cookie({
'name': cookie_name,
'value': cookie_value,
'domain': 'example.com'})
#Display the page after login
driver.get('https://example.com/mypage/')
Now you can see the page after logging in in Firefox.
The add_cookie method works in webdriver.Chrome as well, so you can log in in the same way. Maybe other web drivers will work as well.
When I created HTML of a suitable form locally and set its action = as the login URL, it was requested by GET for some reason even if method = "POST". It seems that recent browsers can no longer send by POST in cross domain, probably because of security.
You may be able to log in by opening the appropriate page of the domain you are logging in to in Selenium, creating a login form in JS, and sending a POST from there. But I haven't done it because it seems to be difficult.
Recommended Posts