kcgklI 2025-04-02 23:00 采纳率: 0%
浏览 9

想提问调用ai模型失败的问题

代码调用ai失败是怎么回事?

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import (NoSuchElementException, 
                                      StaleElementReferenceException,
                                      TimeoutException)
import os
from openai import OpenAI
def click_with_retry(driver, by, value, max_retries=3, delay=1):
    """带重试机制的点击函数"""
    retry = 0
    while retry < max_retries:
        try:
            element = WebDriverWait(driver, 15).until(
                lambda d: d.find_element(by, value))
            element.click()
            return True
        except StaleElementReferenceException:
            retry += 1
            print(f"元素失效,第 {retry} 次重试...")
            time.sleep(delay)
        except Exception as e:
            print(f"点击失败: {e}")
            break
    return False

# 设置手机端的User-Agent
mobile_emulation = {
    "deviceMetrics": {
        "width": 1707,
        "height": 773,
        "pixelRatio": 1.0  # 根据需要调整像素密度
    },
    "userAgent": "Mozilla/5.0 (Linux; Android 13; IQOO 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36"
}
# 创建ChromeOptions对象
chrome_options = Options()
# 启用移动设备模拟
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--ignore-ssl-errors')
# 打开窗口
#这个地方需要你的驱动和你的浏览器版本一致,我这里是116.0.0.0,你可以去浏览器的设置中查看,并且下面的地址也要改成你驱动的地址
chrome_options.binary_location =  r"C:\chrome-win64\chrome-win64\chrome.exe"
wd = webdriver.Chrome(service=Service(r"C:\Users\kcgk\.vscode\chromedriver-win64/chromedriver.exe"), options=chrome_options)
wd.get("https://skl.hduhelp.com/?type=5#/english/list")
wd.maximize_window()
time.sleep(10)
#点击考试
exam = WebDriverWait(wd, 150, 1).until(lambda wd:wd.find_element(By.XPATH,'//*[@id="app"]/div/div[3]/div/div[2]/div[2]/div/button'))
exam.click()
# 点击开始测试,在这之前等等会有效防止网速慢加载不出来
began = WebDriverWait(wd, 150, 1).until(
    lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[2]/div[2]/div/button'))
began.click()
#点击确认
identify = WebDriverWait(wd, 150,1).until(lambda wd:wd.find_element(By.XPATH,'/html/body/div[4]/div[2]/button[2]'))
identify.click()

###开始100次循环
for i in range(100):
    # 获取题目
    question = WebDriverWait(wd, 15, 1).until(
        lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[2]/div/div[1]/span[2]'))
    # 获取选项
    A = WebDriverWait(wd, 15, 0.1).until(
        lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[1]/div[1]/span'))
    B = WebDriverWait(wd, 15, 0.1).until(
        lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[2]/div[1]/span'))
    C = WebDriverWait(wd, 15, 0.1).until(
        lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[3]/div[1]/span'))
    D = WebDriverWait(wd, 15, 0.1).until(
        lambda wd: wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[4]/div[1]/span'))

    # 封装题目
    con = f"""
    {question.text}\n{A.text}\n{B.text}\n{C.text}\n{D.text}
    """
    # 初始化模型
    client = OpenAI(
        #需要你去DEEPSEEK官网注册一个,https://platform.deepseek.com/api_keys,这是网址
        # Deepseek
        # 若没有配置环境变量,请将下行替换为:api_key="你的APIKEY",
        api_key=os.getenv("DEEPSEEK_API_KEY"),
        base_url="https://api.deepseek.com"
    )

    completion = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {'role': 'system',
                'content': 'user提供一个question和4个chioces,根据user的question和choices给出一个答案,要求question和答案选项的意思"相近"!最终回答一个用"--"包起来的大写字母作为答案,例如"--B--"'},
            {'role': 'user', 'content': con.encode("utf-8").decode("utf-8")},
        ]
    )
    # 等待 completion 更新
    WebDriverWait(wd, 10, 0.1).until(lambda wd: '--' in completion.choices[0].message.content)
    print(f"--------{i + 1}  " + completion.choices[0].message.content)

    # 点击选项
    if '--A--' in completion.choices[0].message.content:
                wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[1]/div[1]/span').click()
    if '--B--' in completion.choices[0].message.content:
                wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[2]/div[1]/span').click()
    if '--C--' in completion.choices[0].message.content:
                wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[3]/div[1]/span').click()
    if '--D--' in completion.choices[0].message.content:
                wd.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div/div[3]/div/div[4]/div[1]/span').click()
    # 把completion置空
    completion.choices[0].message.content = None

    # 根据测试结果,这里正常,并且会跳到下一题,那么循环结束
    # 等待下一题加载
    time.sleep(1.5)
time.sleep(1.5)

# 提交
wd.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/div/div/div[3]/span').click()
time.sleep(0.1)
# 点击确认
wd.find_element(By.XPATH, '/html/body/div[4]/div[2]/button[2]').click()
time.sleep(400)


不知道这个创造API之后也充了10元,但是测试的时候不能调用,把开始考试改成自测了

  • 写回答

2条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2025-04-02 23:00
    关注
    让【道友老李】来帮你解答,本回答参考gpt编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!
    根据提供的代码,可能出现代码调用AI失败的情况有以下几个原因:
    1. 网络连接问题导致无法成功加载页面,可以尝试增加等待时间或者检查网络连接是否正常。
    2. 页面元素定位失败,可能是因为页面结构发生变化或者定位方法不准确,可以尝试调整定位方法或者查看页面结构是否有变化。
    3. 代码中使用了OpenAI模块,但是在导入模块时出现错误或者模块未正确安装,可以确认OpenAI模块是否正确导入或者尝试重新安装。
    4. WebDriver或者ChromeDriver版本与浏览器版本不匹配,可以更新驱动程序或者查看浏览器和驱动程序的版本是否一致。 如果要给出实现代码,需要具体了解代码调用AI的部分逻辑和功能,才能给出相应的解决方案。根据提供的代码片段和描述,建议先检查网络连接、页面元素定位、OpenAI模块导入以及WebDriver、ChromeDriver版本等方面是否出现问题。如果仍然无法解决问题,可以提供更多细节信息或者具体的调用AI的代码部分,以便更准确地给出解决方案。
    评论

报告相同问题?

问题事件

  • 创建了问题 4月2日