使用 Selenium 登录并发送 HTTP 请求

python selenium 登录网站后发送 Http 请求

让我搜索一下关于 Python Selenium 和 HTTP 请求相关的内容。

Search

Found 1 result for 'python selenium http status:public'

我找到了一个相关的话题 Python 和 Selenium 的浏览器爬虫,让我来阅读一下具体内容。

Read topic

Reading: Python 和 Selenium 的浏览器爬虫

根据搜索结果,我在论坛上找到了一篇关于 Python 和 Selenium 的详细文章。让我为您总结一下使用 Selenium 实现登录并发送 HTTP 请求的关键点:

  1. 首先需要初始化 Selenium WebDriver:
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.service import Service

chrome = Chrome(service=Service(r"path_to_chromedriver.exe"))
  1. 访问目标网站:
chrome.get('https://example.com')
  1. 登录网站的一般步骤:

    • 找到登录表单元素(使用 find_element 方法)
    • 输入用户名和密码
    • 提交表单
  2. 登录后发送 HTTP 请求的方法:

方法 1:使用 Selenium 的内置请求

  • 直接使用 chrome.get() 访问需要的URL
  • 使用 find_element 获取页面元素

方法 2:获取 Cookie 后用 requests 发送请求

# 获取登录后的 cookies
cookies = chrome.get_cookies()

# 使用 requests 发送请求
import requests
session = requests.Session()

# 设置 cookies
for cookie in cookies:
    session.cookies.set(cookie['name'], cookie['value'])

# 发送 HTTP 请求
response = session.get('https://example.com/api/endpoint')

需要注意的几点:

  1. Selenium 主要是用于自动化测试的工具,但也可以用于爬虫场景
  2. Selenium 的操作会相对较慢,因为需要等待浏览器完全加载
  3. 使用 Selenium 的好处是可以完全模拟真实用户的行为,更容易绕过反爬虫机制

Google 提供的代码

导入库

    from selenium import webdriver

    from selenium.webdriver.common.by import By

    import requests

初始化 WebDriver

    driver = webdriver.Chrome()  # Replace with your browser driver

导航到登录页面

    driver.get("https://www.example.com/login") 

进行登录

找到网页中的元素后设置用户名和密码然后单击登录按钮。

    username_field = driver.find_element(By.ID, "username") 

    username_field.send_keys("your_username") 

    password_field = driver.find_element(By.ID, "password") 

    password_field.send_keys("your_password") 

提交登录表单

提交登录表达就比较简单,直接提交就可以了。

我们主要目的是获得登录后的 Cookie

    login_button = driver.find_element(By.XPATH, "//button[text()='Login']") 

    login_button.click() 

从会话中获得 Cooikes

    cookies = driver.get_cookies()

    session_cookies = {cookie["name"]: cookie["value"] for cookie in cookies}

重新拼装请求

当获得会话的 Cookies 后,重新对需要发送的 Http 请求进行拼装然后发送请求。

    url = "https://www.example.com/protected-page" 

    headers = {"Cookie": "; ".join([f"{key}={value}" for key, value in session_cookies.items()])} 

    response = requests.get(url, headers=headers) 

    print(response.text)