首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python undetectable_webdriver不会在循环中打开

Python undetectable_webdriver不会在循环中打开
EN

Stack Overflow用户
提问于 2021-11-24 17:25:50
回答 1查看 381关注 0票数 0

我试图在一个循环中多次打开一个站点,以测试不同的凭据是否已过期,以便我可以通知我们的用户。我通过打开数据库、获取记录、调用chrome驱动程序打开站点并将值输入到站点来实现这一目标。第一个循环可以工作,但当下一个循环启动时,驱动程序挂起,并最终输出错误:

代码语言:javascript
复制
  "unknown error: cannot connect to chrome at 127.0.0.1:XXXX from chrome not reachable"

当实例已经运行时,通常会发生此错误。当第一个循环完成时,我尝试使用driver.close()和driver.quit()来防止这种情况,但没有效果。我已经处理了所有其他检测的可能性,例如使用代理、不同的用户代理,以及使用undetected_chromedriver by https://github.com/ultrafunkamsterdam/undetected-chromedriver

我希望解决的核心问题是能够打开一个chrome驱动程序的实例,关闭它并在相同的执行循环中再次打开它,直到我测试的所有凭据都完成为止。我已经抽象了代码并提供了一个独立的版本来复制这个问题:

代码语言:javascript
复制
# INSTALL CHROMDRIVER USING "pip install undetected-chromedriver"
import undetected_chromedriver.v2 as uc

# Python Libraries
import time

options = uc.ChromeOptions()

options.add_argument('--no-first-run')

driver = uc.Chrome(options=options)

length = 8
count = 0
if count < length:
    print("Im outside the loop")
    while count < length:
        print("This is loop ",count)
        time.sleep(2)
        with driver:
            print("Im inside the loop")
            count =+ 1
            driver.get("https://google.com")
            time.sleep(5)
            print("Im at the end of the loop")
            driver.quit()   # Used to exit the browser, and end the session
            # driver.close()  # Only closes the window in focus 

我建议使用来保持包的一致性。我在Linux机器上使用python3.9。任何解决方案、建议或解决方案都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-30 21:48:39

您将退出循环中的驱动程序,然后尝试访问已不存在的执行器地址,从而导致错误。您需要重新初始化驱动程序,方法是在循环中,在while语句之前向下移动驱动程序。

代码语言:javascript
复制
from multiprocessing import Process, freeze_support
import undetected_chromedriver as uc

# Python Libraries
import time

chroptions = uc.ChromeOptions()

chroptions.add_argument('--no-first-run enable_console_log = True')
# driver = uc.Chrome(options=chroptions)

length = 8
count = 0
if count < length:
    print("Im outside the loop")
    while count < length:
        print("This is loop ",count)
        driver = uc.Chrome(options=chroptions)
        time.sleep(2)
        with driver:
            print("Im inside the loop")
            count =+ 1
            driver.get("https://google.com")
            print("Session ID: ", end='')  #added to show your session ID is changing
            print(driver.session_id)
            driver.quit()   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70100421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档