即使chrome驱动程序的版本是正确的,我得到一个版本错误

puruo6ea  于 2023-05-11  发布在  Go
关注(0)|答案(1)|浏览(122)

即使ChromeDriver的版本是正确的,我也会得到一个版本错误。
我从来没有安装过ChromeDriver 113版本。(即使在将Chrome驱动程序重新安装到版本112后,也会出现上述错误。还有,另一方面,当我降级到95版本并安装它时,它识别出它是113版本,并导致错误)

  • 即使我安装了一个旧版本的chrome驱动程序作为测试(这是95),“它与版本113不兼容。”错误发生。
  • 我试着删除 chrome 的用户数据,但结果是一样的。(- appdata - local)

下面是错误消息:

Traceback (most recent call last):
  File "C:\Users\no2si\Downloads\eng\newF\23auto_gpt_script.py", line 218, in <module>
    chat_gpt = CustomChatGPT(driver_path, max_retries=3)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\no2si\Downloads\eng\newF\23auto_gpt_script.py", line 26, in __init__
    self.driver = self.attach_to_existing_chrome(driver_path)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\no2si\Downloads\eng\newF\23auto_gpt_script.py", line 43, in attach_to_existing_chrome
    return uc.Chrome(executable_path=driver_path, options=chrome_options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\undetected_chromedriver\__init__.py", line 441, in __init__
    super(Chrome, self).__init__(
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 84, in __init__
    super().__init__(
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 104, in __init__
    super().__init__(
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 286, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\undetected_chromedriver\__init__.py", line 704, in start_session
    super(selenium.webdriver.chrome.webdriver.WebDriver, self).start_session(
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 378, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 440, in execute
    self.error_handler.check_response(response)
  File "C:\Users\no2si\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 245, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:56479
from session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 112.0.5611.0
Stacktrace:
Backtrace:
        GetHandleVerifier [0x003C8893+48451]
        (No symbol) [0x0035B8A1]
        (No symbol) [0x00265058]
        (No symbol) [0x00285D9C]
        (No symbol) [0x00280151]
        (No symbol) [0x0027FF31]
        (No symbol) [0x002B0798]
        (No symbol) [0x002B047C]
        (No symbol) [0x002AA0B6]
        (No symbol) [0x00287E08]
        (No symbol) [0x00288F2D]
        GetHandleVerifier [0x00628E3A+2540266]
        GetHandleVerifier [0x00668959+2801161]
        GetHandleVerifier [0x0066295C+2776588]
        GetHandleVerifier [0x00452280+612144]
        (No symbol) [0x00364F6C]
        (No symbol) [0x003611D8]
        (No symbol) [0x003612BB]
        (No symbol) [0x00354857]
        BaseThreadInitThunk [0x76D96B89+25]
        RtlGetFullPathName_UEx [0x77CF8F9F+1215]
        RtlGetFullPathName_UEx [0x77CF8F6D+1165]

这是自动向聊天gpt输入消息的代码。

import json
import requests
from urllib.request import urlopen
import os
import time
import re
import datetime
import random
import undetected_chromedriver as uc
import keyboard
import tempfile
from threading import Timer
from inputimeout import inputimeout as input, TimeoutOccurred as TimeoutError
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import TimeoutException

class CustomChatGPT:
    def __init__(self, driver_path, max_retries=3):
        self.driver_path = driver_path
        self.driver = self.attach_to_existing_chrome(driver_path)
        self.text_group_a = "text_group_a.txt"
        self.text_group_b = "text_group_b.txt"
        self.MAX_RETRIES = max_retries
        self.paused = False  # Add this line to initialize the 'paused' attribute

    def launch_new_chrome_instance(self):
        chrome_options = self.set_chrome_options()
        return uc.Chrome(executable_path=self.driver_path, options=chrome_options)

    def attach_to_existing_chrome(self, driver_path):
        temp_dir = tempfile.mkdtemp()  # Create a temporary directory
        chrome_options = uc.ChromeOptions()
        chrome_options.add_argument(f"user-data-dir={temp_dir}")  # Use the temporary directory as user-data-dir
        # Remove the following line:
        # chrome_options.add_argument("--remote-debugging-port=9222")
        chrome_options.binary_location = r"C:\Users\no2si\Downloads\ch112 re\chrome-win\chrome.exe"
        return uc.Chrome(executable_path=driver_path, options=chrome_options)

    def create_new_chat_box(self):
        new_chat_button = WebDriverWait(self.driver, 30).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@id="__next"]/div[2]/div[1]/div/div/nav/a'))
        )
        new_chat_button.click()

    def wait_for_user_new_chat(self):
        print("Please create a new chat manually and press Enter when ready.")
        input()

    def send_text(self, text):
        try:
            input_box = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[2]/div[2]/main/div[2]/form/div/div[2]/textarea"))
            )
            input_box.click()
            time.sleep(1)  # Add a 1-second delay before sending the text

            actions = ActionChains(self.driver)
            for char in text:
                if char == '\n':
                    actions.key_down(Keys.SHIFT).send_keys(Keys.ENTER).key_up(Keys.SHIFT)
                else:
                    actions.send_keys(char)
            actions.perform()

            send_button = WebDriverWait(self.driver, 2).until(
                EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div[2]/div[2]/main/div[2]/form/div/div[2]/button"))
            )
            send_button.click()
        except TimeoutException:
            print("Error finding input box or send button. Please try again.")

    def close_website(self):
        self.driver.quit()

    def process_group_b(self, file_path):
        with open(file_path, "r", encoding="utf-8") as file:
            content = file.read()

        bundles = []
        start_marker = "##tegst-"
        end_marker = "##tegov-"
        index = 1

        while True:
            start_tag = f"{start_marker}{index}##"
            end_tag = f"{end_marker}{index}##"

            start_pos = content.find(start_tag)
            end_pos = content.find(end_tag)

            if start_pos == -1 or end_pos == -1:
                break

            bundle = content[start_pos + len(start_tag):end_pos].strip()
            bundles.append(bundle)

            index += 1

        return bundles

    def check_content_policy_message(self):
            try:
                content_policy_message = WebDriverWait(self.driver, 10).until(
                    EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'py-2') and contains(@class, 'px-3') and contains(@class, 'border') and contains(@class, 'text-sm') and a[contains(@href, 'https://platform.openai.com/docs/usage-policies/content-policy')]]"))
                )
                return content_policy_message
            except TimeoutException:
                return None

    def wait_for_chat_limit_reset(self):
        try:
            chat_limit_message = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//span[contains(text(), 'You\'ve reached the current usage cap for GPT-4')] | //div[contains(span, 'You\'ve reached the current usage cap for GPT-4')]"))
            )
            wait_time_hour, wait_time_minute, am_pm = self.parse_wait_time(chat_limit_message.text)
            wait_time_seconds = self.calculate_wait_time_seconds(wait_time_hour, wait_time_minute, am_pm)
            return wait_time_seconds
        except TimeoutException:
            return None

    def parse_wait_time(self, wait_time_text):
        wait_time_hour = int(re.search(r'(?<=after\s)\d+(?=:)', wait_time_text).group())
        wait_time_minute = int(re.search(r'(?<=:)\d+', wait_time_text).group())
        am_pm = re.search(r'(?<=\d+\s)[A|P]M', wait_time_text).group()
        return wait_time_hour, wait_time_minute, am_pm

    def resume_processing(self, index):
        wait_time_seconds = self.wait_for_chat_limit_reset()

        if wait_time_seconds:
            print(f"Reached chat count limit. Waiting for {wait_time_seconds} seconds.")
            time.sleep(wait_time_seconds)
            self.create_new_chat_box()
            self.open_gpt_version_menu()
            self.select_gpt_version(4)
            self.process_bundle_with_retry(text_group_a, bundles[index], index)

    def calculate_wait_time_seconds(self, wait_time_hour, wait_time_minute, am_pm):
        now = datetime.datetime.now()
        target_time = now.replace(hour=wait_time_hour % 12 + 12 * (am_pm == 'PM'), minute=wait_time_minute, second=0, microsecond=0)

        if target_time < now:
            target_time = target_time + datetime.timedelta(days=1)

        delta = target_time - now
        return delta.total_seconds()

    def pause_execution(self):
        print("Press Enter within 3 seconds to pause execution.")
        try:
            input("", timeout=3)
            self.paused = not self.paused
        except TimeoutError:
            pass

    def get_starting_bundle_index(self):
        while True:
            try:
                index = int(input("Enter the starting bundle index: "))
                return index - 1
            except ValueError:
                print("Invalid input. Please enter a valid integer.")

    def process_bundle_with_retry(self, text_group_a, bundle, index):
        start_marker = "##tegst-"
        end_marker = "##tegov-"
    
        combined_text = text_group_a + "\n\n" + start_marker + bundle + end_marker
        retry_count = 0

        while retry_count < self.MAX_RETRIES:
            self.pause_execution()
            if not self.paused:
                try:
                    self.send_text(combined_text)
                    time.sleep(240)  # Add a 4-minute delay after sending the text
                    break
                except Exception as e:
                    print(f"Error occurred while processing bundle {index}: {e}")
                    retry_count += 1
                    if retry_count == self.MAX_RETRIES:
                        print(f"Failed to process bundle {index} after {self.MAX_RETRIES} retries.")
            else:
                print("Execution paused.")
                input("Press Enter to resume.")
                self.paused = False

    def automate_chat_gpt(self, url, text_group_a, file_path):
        try:
            self.driver.get(url)
            self.wait_for_user_new_chat()
            time.sleep(5)

            bundles = self.process_group_b(file_path)
            starting_index = self.get_starting_bundle_index()

            for index, bundle in enumerate(bundles[starting_index:], start=starting_index):
                self.process_bundle_with_retry(text_group_a, bundle, index)
                print(f"Processing of the {index + 1}th bundle complete.") 
        except Exception as e:
            print(f"An error occurred: {e}")

if __name__ == "__main__":
    text_group_a = """If I give you a sentence, process it according to the following conditions.
1. Among the words in the following sentences, change Nouns, pronouns, verbs, adjectives, and adverbs to easier words.

2. Keep Paragraph Line Breaks and Marks

here is the sentence: """
    chat_gpt_url = "https://chat.openai.com"
    driver_path = r"C:\Users\no2si\Documents\CChromedriver\chromedriver.exe"
    chat_gpt = CustomChatGPT(driver_path, max_retries=3)
    file_path = r"C:\Users\no2si\Downloads\eng\output2.txt" # Replace with the correct path to your file
    chat_gpt.automate_chat_gpt(chat_gpt_url, text_group_a, file_path)
1rhkuytd

1rhkuytd1#

为了解决这个问题,我检查了可用的版本。我使用的是snap在ubuntu 20.04上安装的chromium:

$ sudo snap info chromium
name:      chromium
summary:   Chromium web browser, open-source version of Chrome
publisher: Canonical✓
...
channels:
  latest/stable:    112.0.5615.49  2023-04-11 (2424) 156MB -
  latest/candidate: 112.0.5615.165 2023-04-20 (2450) 156MB -
  latest/beta:      113.0.5672.63  2023-05-01 (2455) 157MB -
  latest/edge:      114.0.5735.6   2023-05-03 (2458) 155MB -
installed:          112.0.5615.49             (2424) 156MB -

然后我安装了版本113,这是“测试版”通道:

$ sudo snap refresh --beta chromium
Download snap "chromium" (2455) from channel "latest/beta"    76%  9.6MB/s 2.60s
...
Mount snap "chromium" (2455)                                                   \
chromium (beta) 113.0.5672.63 from Canonical✓ refreshed

相关问题