Selenium webdriver: «сеанс не создан - Chrome не доступен» при использовании скопированного хромированного профиляPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Selenium webdriver: «сеанс не создан - Chrome не доступен» при использовании скопированного хромированного профиля

Сообщение Anonymous »

Я пытаюсь автоматизировать Chrome, используя Selenium, создав новый Chrome Profile, копируя содержимое профиля по умолчанию и запустив его с Selenium для извлечения файлов cookie. Тем не менее, я продолжаю сталкиваться с следующей ошибкой: < /p>

Код: Выделить всё

selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from chrome not reachable
Full Traceback

Код: Выделить всё

Traceback (most recent call last):
File "test.py", line 71, in g_chrome_cookies
driver = webdriver.Chrome(service=service, options=options)
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__
super().__init__(
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 66, in __init__
super().__init__(command_executor=executor, options=options)
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 250, in __init__
self.start_session(capabilities)
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 342, in start_session
response = self.execute(Command.NEW_SESSION, caps)["value"]
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from chrome not reachable
Кроме того, я также попытался использовать-remote-debugging-pipe, но это приводит к ошибке тайм-аута.
среда:

Код: Выделить всё

OS: Windows 10 / 11 (tested on three machines)

Chrome Version: 136.0.7103.93 (64-bit)

ChromeDriver Version: 4.0.2 (managed by webdriver-manager)

Selenium Version: 4.31.0

Python Version: 3.9.5
Я проверил это на трех разных машинах Windows, и ошибка идентична для всех из них.
code
import os
import shutil
import getpass
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from traceback import format_exc

def copy_profile():
"""Copy Chrome 'Default' profile to a new profile folder 'Profile X' where X is the next available number."""
username = getpass.getuser()
base_path = rf"C:\Users\{username}\AppData\Local\Google\Chrome\User Data"
src_path = os.path.join(base_path, "Default")

# Find next available Profile number
for i in range(1, 100):
dest_path = os.path.join(base_path, f"Profile {i}")
if not os.path.exists(dest_path):
break

print(f"Copying profile from:\n {src_path}\nto:\n {dest_path}")
shutil.copytree(src_path, dest_path)
return dest_path

def g_chrome_cookies(profile_name):
"""Launch Chrome with a specific profile and get cookies from Facebook."""
username = getpass.getuser()
user_data_dir = rf"C:\Users\{username}\AppData\Local\Google\Chrome\User Data"

if not os.path.exists(user_data_dir):
raise FileNotFoundError(f"Chrome user data directory not found: {user_data_dir}")

options = Options()
options.add_argument("--disable-gpu")
options.add_argument("--disable-software-rasterizer")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
options.add_argument("--disable-extensions")
# options.add_argument('--remote-debugging-pipe') # I have checked this option but it causes a timeout error
options.add_argument(f"user-data-dir={user_data_dir}")
options.add_argument(f'--profile-directory={profile_name}')
# Uncomment the next line if you want headless mode
# options.add_argument("--headless=new")

os.environ["QT_LOGGING_RULES"] = "qt.sql.sqlite.warning=false"
service = Service(ChromeDriverManager().install())

driver = None
try:
driver = webdriver.Chrome(service=service, options=options)
driver.get("https://www.facebook.com/")
cookies = driver.get_cookies()
return {cookie['name']: cookie['value'] for cookie in cookies}
except Exception:
print(format_exc())
return {}
finally:
if driver:
driver.quit()

def generate_cookies():
print("[+] Creating new Chrome profile")
new_profile_path = copy_profile()

try:
profile_number = new_profile_path.split("Profile")[-1].strip()
profile_name = f"Profile {profile_number}"
cookies = g_chrome_cookies(profile_name)
print("[+] Retrieved cookies:", cookies)
except Exception:
print(format_exc())
finally:
print("[+] Deleting the copied profile folder")
if os.path.exists(new_profile_path):
shutil.rmtree(new_profile_path)

if __name__ == "__main__":
generate_cookies()
< /code>
Что я пробовал: < /strong> < /p>

Использование имен профилей < /li>
Добавление-remote-debugging-pipe (результаты в времени ожидания) < /li>
Обеспечение того, как указывается на управление пользователями, и может быть доступен в Li>
. и chromedriver
версии < /li>
< /ul>

Подробнее здесь: https://stackoverflow.com/questions/796 ... using-a-co
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»