Python Selenium自动化访问ChatGPT实战指南:从环境搭建到避坑技巧

2次阅读
没有评论

共计 2914 个字符,预计需要花费 8 分钟才能阅读完成。

image.webp

为什么选择 Selenium 访问 Web 应用

Selenium 作为主流的 Web 自动化测试工具,在模拟用户操作方面具有独特优势:

Python Selenium 自动化访问 ChatGPT 实战指南:从环境搭建到避坑技巧

  • 支持多浏览器(Chrome/Firefox/Edge 等)的真实渲染环境
  • 能处理 JavaScript 动态生成的内容
  • 提供丰富的 API 定位页面元素
  • 可录制和回放操作流程

这些特性使其成为访问 ChatGPT 这类 SPA(单页应用)的理想工具。

ChatGPT 特有的技术挑战

1. 动态元素标识

ChatGPT 前端使用 React 框架,页面元素的 idclass属性经常随版本更新变化。例如:

<!-- 旧版本 -->
<textarea id="prompt-textarea"></textarea>

<!-- 新版本可能变为 -->
<div class="request-textarea"></div>

2. 反爬机制

  • 请求频率检测(单位时间内操作次数限制)
  • 鼠标轨迹分析
  • 浏览器指纹识别

3. 验证码系统

当检测到异常访问时,会触发 reCAPTCHA 验证。

完整实现方案

环境准备

  1. 安装必要库:
pip install selenium webdriver-manager
  1. ChromeDriver 自动管理(无需手动下载):
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())

核心代码实现

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import random

class ChatGPTAutomation:
    def __init__(self):
        options = webdriver.ChromeOptions()

        # 生产环境建议开启无头模式
        # options.add_argument("--headless")  

        # 禁用自动化控制标志
        options.add_argument("--disable-blink-features=AutomationControlled")

        self.driver = webdriver.Chrome(service=service, options=options)
        self.wait = WebDriverWait(self.driver, 15)

    def login(self, username, password):
        """处理登录流程"""
        self.driver.get("https://chat.openai.com/auth/login")

        # 使用显式等待定位动态元素
        login_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Log in')]"))
        )
        login_btn.click()

        # 模拟人类输入间隔
        self._human_type("//input[@name='username']", username)
        self._human_type("//input[@name='password']", password)

        # 随机延迟 1 - 3 秒
        time.sleep(random.uniform(1, 3))  

    def send_prompt(self, text):
        """发送问题并获取响应"""
        try:
            textarea = self.wait.until(EC.presence_of_element_located((By.TAG_NAME, "textarea"))
            )
            textarea.send_keys(text)

            submit_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class,'submit')]"))
            )
            submit_btn.click()

            # 等待响应完成
            self.wait.until(EC.presence_of_element_located((By.XPATH, "//div[contains(@class,'response')]"))
            )

            return self._get_last_response()
        except Exception as e:
            print(f"请求失败: {str(e)}")
            self._handle_error()

    def _human_type(self, xpath, text):
        """模拟人类输入节奏"""
        elem = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
        for char in text:
            elem.send_keys(char)
            time.sleep(random.uniform(0.1, 0.3))

    def _get_last_response(self):
        """获取最新响应内容"""
        responses = self.driver.find_elements(By.XPATH, "//div[contains(@class,'response')]")
        return responses[-1].text if responses else ""def _handle_error(self):""" 异常处理 """
        # 添加重试或验证码处理逻辑
        pass

生产环境注意事项

1. IP 封禁应对

  • 使用代理 IP 轮换(推荐 Luminati 等商业服务)
  • 配合住宅代理模拟真实用户
  • 单个 IP 请求间隔建议 >30 秒

2. 请求频率优化

# 在每次操作后添加随机延迟
time.sleep(random.uniform(2, 5))

# 每 10 次请求后长暂停
if request_count % 10 == 0:
    time.sleep(random.uniform(30, 60))

3. 无头模式调试

# 启用调试模式
options.add_argument("--remote-debugging-port=9222")

# 截图记录关键步骤
self.driver.save_screenshot("debug.png")

进阶思考

  1. 如何通过浏览器指纹混淆技术绕过高级反爬检测?
  2. 当遇到 reCAPTCHA 验证时,有哪些自动化解决方案?(提示:考虑第三方 API 服务)
  3. 在分布式环境下如何设计任务调度系统实现大规模自动化采集?

总结

通过本文介绍的技术方案,开发者可以构建稳定的 ChatGPT 自动化交互系统。关键点在于:使用可靠的元素定位策略、模拟人类操作模式、实施完善的错误处理机制。建议在实际应用中持续监控脚本表现,及时调整反反爬策略以适应目标网站的变化。

正文完
 0
评论(没有评论)