Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Requests library with Selenium, in Python

I would like to log into a webpage using Selenium and use the logged in session to do subsequent requests using the Requests library. My code so far is as shown:

from selenium import webdriver
import requests

driver = webdriver.Chrome()
driver.get("https://www.linkedin.com/uas/login?") 

Once I get to the log in page I simply put in my login details then once logged in I want to be able to get info from specific pages using the requests library instead. How can I get this working?

like image 765
West Avatar asked May 07 '26 11:05

West


1 Answers

Ok just figured this out for anyone with this challenge. Its simply passing the cookies from selenium to the requests session:

from selenium import webdriver
import requests

driver = webdriver.Chrome()
driver.get("https://www.linkedin.com/uas/login?")

s = requests.Session()
# Set correct user agent
selenium_user_agent = driver.execute_script("return navigator.userAgent;")
s.headers.update({"user-agent": selenium_user_agent})

for cookie in driver.get_cookies():
    s.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'])

response = s.get("https://linkedin/example_page.com")
like image 200
West Avatar answered May 11 '26 03:05

West



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!