简体   繁体   English

如何在 Python 中将 Requests 库与 Selenium 一起使用

[英]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.我想使用 Selenium 登录网页,并使用登录的 session 使用 Requests 库执行后续请求。 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?我怎样才能得到这个工作?

Ok just figured this out for anyone with this challenge.好的,只是为有此挑战的任何人解决了这个问题。 Its simply passing the cookies from selenium to the requests session:它只是将 cookies 从 selenium 传递给请求 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM