Selenium驱动程序在操作系统警告框上卡住了。

5
我在Python(3.11)中使用Firefox(107)驱动程序来使用Selenium。使用驱动程序导航到页面后,执行多个操作会触发一个OS警报(提示我启动程序)。当这个警报弹出时,驱动程序卡住了,只有手动关闭它后,我的脚本才能继续运行。 我尝试过使用driver.quit(),也尝试使用
os.system("taskkill /F /pid " + str(process.ProcessId))

尝试使用驱动程序的PID,但没有成功。

我已经成功阻止了弹出窗口的出现。

options.set_preference("security.external_protocol_requires_permission", False)

但代码仍然在弹出窗口将会出现的位置挂起。

我不关心程序是否启动,我只需要我的代码不需要人为干预即可通过这一关键点。

以下是我目前拥有的最简示例:

from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.firefox.options import Options
from seleniumwire import webdriver

options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options.set_preference("security.external_protocol_requires_permission", False)
driver = webdriver.Firefox(options=options)

# Go to the page
driver.get(url)

user_field = driver.find_element("id", "UserName")
user_field.send_keys(username)
pass_field = driver.find_element("id", "Password")
pass_field.send_keys(password)
pass_field.send_keys(Keys.ENTER)

#this is the point where the pop up appears

reqs = driver.requests

print("Success!")
driver.quit()

对我来说,程序会停顿一段时间,但几秒钟后代码会正常执行。你是想消除这种延迟吗?还是你的程序会无限期地停顿? - Lucan
@Lucan Mine无限期停止。我甚至在午餐时间离开它,只是为了确保。 - Jessica Chambers
发送凭据后显示的对话框(弹出窗口)是什么?为什么不用代码关闭对话框? - Life is complex
对话框与在评论中发布的截图几乎相同。我不知道如何用代码关闭它,这就是我的问题的本质。 - Jessica Chambers
3个回答

3

你可以尝试一些偏好设置

profile = webdriver.FirefoxProfile()
profile.set_preference('dom.push.enabled', False)

# or

profile = webdriver.FirefoxProfile()
profile.set_preference('dom.webnotifications.enabled', False)
profile.set_preference('dom.webnotifications.serviceworker.enabled', False)

3

您尝试将此首选项设置以防止特定弹出窗口吗:

profile.set_preference('browser.helperApps.neverAsk.openFile', 'typeOfFile')  
# e.g. profile.set_preference('browser.helperApps.neverAsk.openFile', 'application/xml,application/octet-stream')

或者您尝试过直接关闭弹窗吗:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

....
pass_field.send_keys(Keys.ENTER)

#this is the point where the pop up appears
WebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()
reqs = driver.requests
...

我还没有尝试过它们中的任何一个,但它们看起来很有前途! - Jessica Chambers
1
让我知道进展如何。如果不行的话,也许你可以给我更多的代码,这样我就可以重新创建这个问题。 - mr_mooo_cow
Selenium无法识别那种警报,WebDriverWait在这里不起作用。 - Guy

1
手动勾选此复选框,然后对于您使用的每个链接相关的应用程序打开应用程序,然后它将正常工作。
请参考以下截图: enter image description here

嗨,我尝试了这个,但是Firefox要么不真正记住,要么它不起作用。 - Jessica Chambers
为了让它正常工作,您可能需要在Firefox中使用一个配置文件。Selenium默认情况下会使用一个全新的配置文件。在这里,我找到了一个加载默认配置文件的答案:https://dev59.com/Ca7la4cB1Zd3GeqPfpiK#52474787 - r000bin
@r000bin,我该如何提取/导出包含此复选框更改的Firefox配置文件? - Jessica Chambers
1
在这里,您可以找到配置文件以及包含您更改的文件:https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data#:~:text=Firefox%20stores%20your%20profile%20folder%20in%20this%20location,folder%20as%20follows%3A%20Click%20the%20Windows%20Start%20button. - r000bin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接