# 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-hk/dai-li/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.
