# 使用 Selenium 登录并发送 HTTP 请求

**URL:** <https://www.isharkfly.com/t/selenium-http/16642>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [November 21, 2024, 6:52pm UTC](https://www.isharkfly.com/t/selenium-http/16642 "2024-11-21T18:52:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 21, 2024, 6:52pm UTC](https://www.isharkfly.com/t/selenium-http/16642/1 "2024-11-21T18:52:32Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [November 21, 2024, 6:52pm UTC](https://www.isharkfly.com/t/selenium-http/16642/2 "2024-11-21T18:52:33Z")

</div>

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

> **Search**
>
> Found 1 [result](https://www.isharkfly.com/search?q=python+selenium+http+status%3Apublic) for 'python selenium http status:public'

我找到了一个相关的话题 [Python 和 Selenium 的浏览器爬虫](https://www.isharkfly.com/t/python-selenium/14988/1)，让我来阅读一下具体内容。

> **Read topic**
>
> Reading: [Python 和 Selenium 的浏览器爬虫](https://www.isharkfly.com/t/python-selenium/14988)

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

1. 首先需要初始化 Selenium WebDriver：

```python
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.service import Service

chrome = Chrome(service=Service(r"path_to_chromedriver.exe"))

```

1. 访问目标网站：

```python
chrome.get('https://example.com')

```

1. 登录网站的一般步骤：

2. 登录后发送 HTTP 请求的方法：

**方法 1：使用 Selenium 的内置请求**

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

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

```python
# 获取登录后的 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 提供的代码

### 导入库

```auto
    from selenium import webdriver

    from selenium.webdriver.common.by import By

    import requests

```

### 初始化 WebDriver

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

```

### 导航到登录页面

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

```

### 进行登录

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

```auto
    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

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

    login_button.click() 

```

### 从会话中获得 Cooikes

```auto
    cookies = driver.get_cookies()

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

```

### 重新拼装请求

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

```auto
    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)

```

---

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 21, 2024, 6:53pm UTC](https://www.isharkfly.com/t/selenium-http/16642/3 "2024-11-21T18:53:34Z")

</div>

Made this topic public on November 21, 2024, 6:53pm UTC


