如果你决定使用 Selenium 进行自动化,以下是一个结合 FastAPI 和 Selenium 的示例:
首先,确保已安装 Selenium 和 FastAPI 的 Python 包:
pip install selenium fastapi
然后,你需要下载适用于你使用的浏览器的 Selenium WebDriver。例如,如果你使用 Chrome 浏览器,可以下载 Chrome WebDriver。
接下来,根据你的需求,将以下代码添加到 FastAPI 应用程序中:
from fastapi import FastAPI
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
app = FastAPI()
@app.post("/register")
def register_user(username: str, password: str):
# 配置 Selenium Chrome WebDriver
chrome_options = Options()
chrome_options.add_argument("--headless") # 无头模式运行浏览器,不会打开浏览器窗口
service = Service('/path/to/chromedriver') # 替换为你的 Chrome WebDriver 路径
driver = webdriver.Chrome(service=service, options=chrome_options)
# 打开第三方注册页面
driver.get("https://third-party-website.com/register")
# 在注册页面填写表单
username_input = driver.find_element(By.ID, "username")
username_input.send_keys(username)
password_input = driver.find_element(By.ID, "password")
password_input.send_keys(password)
# 提交表单
submit_button = driver.find_element(By.ID, "submit")
submit_button.click()
# 等待页面加载完成并获取结果
driver.implicitly_wait(10) # 等待 10 秒钟
result_element = driver.find_element(By.ID, "result")
result = result_element.text
# 关闭浏览器
driver.quit()
return {"message": result}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
在上述示例中,我们导入了 Selenium 相关的模块,并使用 Chrome WebDriver 进行演示。你需要根据你使用的浏览器和 WebDriver 的类型进行相应的调整。
在 /register 路由中,我们使用 Selenium WebDriver 打开第三方注册页面,并使用 find_element 方法找到相关的表单元素,然后使用 send_keys 方法填充表单数据。最后,我们使用 click 方法提交表单,并等待页面加载完成以获取结果。
请注意,使用 Selenium 进行自动化时,你需要了解目标网站的 HTML 结构和表单元素的标识方式(例如 ID、类名、XPath 等),并相应地调整代码。
启动 FastAPI 应用程序后,你可以使用类似以下的请求向 /register 路由发送 POST 请求:
import requests
url = "http://localhost:8000/register"
payload = {
"username": "your_username",
"password": "your_password"
}
response = requests.post(url, json=payload)
print(response.json())
这将向 FastAPI 应用程序发送注册请求,并返回第三方注册的结果。
请确保在实际使用中提供正确的 WebDriver 路径,并根据目标网站的实际情况进行相应的修改。