使用Python的selenium库实现带cookie的网页请求可以按照以下步骤进行:

  1. 安装selenium库:在命令提示符或终端中运行以下命令安装selenium库:
pip install selenium
  1. 下载并安装对应浏览器的驱动程序:selenium需要使用浏览器驱动程序来控制浏览器,可以根据使用的浏览器下载对应的驱动程序,例如Chrome浏览器需要下载ChromeDriver。

  2. 导入selenium库和WebDriver类:在Python脚本中导入selenium库和WebDriver类,以及需要使用的其他类和方法。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
  1. 创建WebDriver对象并设置浏览器选项:根据使用的浏览器和驱动程序的路径创建WebDriver对象,并设置浏览器选项,如启用无头模式。
# 设置Chrome浏览器选项
chrome_options = Options()
chrome_options.add_argument('--headless')  # 启用无头模式

# 创建Chrome浏览器的WebDriver对象
driver = webdriver.Chrome(service=Service('path_to_chromedriver'), options=chrome_options)

其中,path_to_chromedriver为ChromeDriver的路径。

  1. 设置cookie:通过WebDriver对象的add_cookie方法设置cookie。可以使用driver.add_cookie方法将cookie添加到浏览器会话中。
# 设置cookie
cookie_str = '__wsi1=33987f8b81302a8efe3ed3b1ed7e4a7df35c0346; __wsi2=47d70c1f1ddd605c06366c223c6e7c2769b328bb; __wsi3=770ba60c7c8777c8f0450199c8947f65f60a960d; ts_session_id_=Wx5lZ11lsra8Q4C8rWJT0510XAHYbOjqYEZfiRKS'
cookies = [{'name': c.split('=')[0], 'value': c.split('=')[1]} for c in cookie_str.split('; ')]
for cookie in cookies:
    driver.add_cookie(cookie)
  1. 发起请求:使用WebDriver对象的get方法访问指定的URL,并等待页面加载完成。
# 发起请求
url = 'https://jx3.seasunwbl.com/buyer?t=skin'
driver.get(url)
driver.implicitly_wait(10)  # 等待页面加载完成,最多等待10秒
  1. 获取响应内容:使用WebDriver对象的page_source属性获取页面的HTML内容。
# 获取响应内容
response = driver.page_source
print(response)
  1. 关闭浏览器:使用WebDriver对象的quit方法关闭浏览器。
# 关闭浏览器
driver.quit()

完整的代码示例:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 设置Chrome浏览器选项
chrome_options = Options()
chrome_options.add_argument('--headless')  # 启用无头模式

# 创建Chrome浏览器的WebDriver对象
driver = webdriver.Chrome(service=Service('path_to_chromedriver'), options=chrome_options)

# 设置cookie
cookie_str = '__wsi1=33987f8b81302a8efe3ed3b1ed7e4a7df35c0346; __wsi2=47d70c1f1ddd605c06366c223c6e7c2769b328bb; __wsi3=770ba60c7c8777c8f0450199c8947f65f60a960d; ts_session_id_=Wx5lZ11lsra8Q4C8rWJT0510XAHYbOjqYEZfiRKS'
cookies = [{'name': c.split('=')[0], 'value': c.split('=')[1]} for c in cookie_str.split('; ')]
for cookie in cookies:
    driver.add_cookie(cookie)

# 发起请求
url = 'https://jx3.seasunwbl.com/buyer?t=skin'
driver.get(url)
driver.implicitly_wait(10)  # 等待页面加载完成,最多等待10秒

# 获取响应内容
response = driver.page_source
print(response)

# 关闭浏览器
driver.quit()

注意替换代码中的path_to_chromedriver为ChromeDriver的实际路径。


原文地址: https://www.cveoy.top/t/topic/piym 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录