我试图在一个循环中多次打开一个站点,以测试不同的凭据是否已过期,以便我可以通知我们的用户。我通过打开数据库、获取记录、调用chrome驱动程序打开站点并将值输入到站点来实现这一目标。第一个循环可以工作,但当下一个循环启动时,驱动程序挂起,并最终输出错误:
"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驱动程序的实例,关闭它并在相同的执行循环中再次打开它,直到我测试的所有凭据都完成为止。我已经抽象了代码并提供了一个独立的版本来复制这个问题:
# 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。任何解决方案、建议或解决方案都将不胜感激。
发布于 2021-11-30 21:48:39
您将退出循环中的驱动程序,然后尝试访问已不存在的执行器地址,从而导致错误。您需要重新初始化驱动程序,方法是在循环中,在while语句之前向下移动驱动程序。
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() https://stackoverflow.com/questions/70100421
复制相似问题