# Selenium

#### 什么是Selenium？

[**Selenium**](https://www.selenium.dev/)是一系列工具和函式库的总括项目，可实现和支援Web浏览器的自动化。

Selenium有许多功能，但其核心是一个用于Web浏览器自动化的工具集，它使用可用的最佳技术来远端控制浏览器实例并模拟使用者与浏览器的互动。

<figure><img src="/files/LNdaz8cE21yeqSpF3rXm" alt=""><figcaption></figcaption></figure>

下面为您介绍如何将Thordata与Selenium集成。

{% stepper %}
{% step %}

### 安装Selenium

安装 Selenium Wire来扩充 Selenium的Python绑定，因为使用预设的Selenium模组来实现需要身份验证的代理程式会使整个过程变得复杂。您可以使用pip指令来完成此操作：`pip install selenium-wire`

此整合的另一个推荐包是 `webdriver-manager`。它是一个简化不同浏览器二进位驱动程式管理的套件。在这种情况下，无需在每次更新后手动下载新版本的 Web 驱动程式。
{% endstep %}

{% step %}

### 指定您的使用者凭证以使代理程式正常运作

`USERNAME = "td-customer-USERNAME"`

`PASSWORD = "PASSWORD"`

`ENDPOINT = "t.pr.thordata.net:9999"`
{% endstep %}

{% step %}

### 检查代理状态

通过访问`ipinfo.thordata.com`检查代理是否正常运作。如果一切正常 - 它将传回您正在使用的代理程式的 IP 位址。

```
try:
    driver.get("https://ipinfo.thordata.com/")
    return f'\nYour IP is: {driver.find_element(By.CSS_SELECTOR, "pre").text}'
finally:
    driver.quit()
```

{% endstep %}
{% endstepper %}

**完整代码示例：**

```
from selenium.webdriver.common.by import By
from seleniumwire import webdriver
# A package to have a chromedriver always up-to-date.
from webdriver_manager.chrome import ChromeDriverManager

USERNAME = "td-customer-USERNAME"
PASSWORD = "PASSWORD"
ENDPOINT = "t.pr.thordata.net:9999"

def chrome_proxy(user: str, password: str, endpoint: str) -> dict:
    wire_options = {
        "proxy": {
            "http": f"http://{user}:{password}@{endpoint}",
            "https": f"https://{user}:{password}@{endpoint}",
        }
    }

    return wire_options

def execute_driver():
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    proxies = chrome_proxy(USERNAME, PASSWORD, ENDPOINT)
    driver = webdriver.Chrome(
    ChromeDriverManager(driver_version='<VERSION>').install(), options=options, seleniumwire_options=proxies
    )
    try:
        driver.get("https://ipinfo.thordata.com/")
        return f'\nYour IP is: {driver.find_element(By.CSS_SELECTOR, "pre").text}'
    finally:
        driver.quit()


if __name__ == '__main__':
    print(execute_driver())
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.thordata.com/doc/zh/proxies/ji-cheng-jiao-cheng/zhu-zhai-dai-li-ji-cheng/selenium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
