通过Python selenium安装chrome扩展时出错

2024-06-02 07:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pythonselenium安装chrome扩展。 当我点击addtochrome按钮时,会产生一个弹出窗口(不知道它是否是java脚本),询问:“addextension”,“Cancel”。我想单击“添加扩展名”,但我收到以下错误:

selenium.common.exceptions.NoAlertPresentException: Message: no alert open

我的代码:

from selenium import webdriver
import time

driver=webdriver.Chrome()
driver.implicitly_wait(30)
driver.get("https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en")
time.sleep(15)
element=driver.find_element_by_css_selector("body > div.F-ia-k.S-ph.S-Rc-qa > div.h-F-f-k.F-f-k > div > div > div.e-f-o > div.h-e-f-Ra-c.e-f-oh-Md-zb-k > 
div.dd-Va.g-c-wb.g-eg-ua-Uc-c-za.g-c-Oc-td-jb-oa.g-c")
element.click()
alert = driver.switch_to.alert
alert.accept() 

帮我安装一下。在

更新代码:

^{pr2}$

Tags: 代码importdiv脚本timedriverseleniumalert
1条回答
网友
1楼 · 发布于 2024-06-02 07:38:32

这是因为您尝试使用switch_to.alert选择的下载选项弹出窗口实际上不是JS警报弹出窗口。您不能选择is using Selenium的switch_to方法。您需要使用DesiredCapabilities类来选择这个选项,然后在代码中使用它。在

根据ChromeDriver文档,给定here,请使用压缩的(扩展名为.crx的文件)或未打包的扩展文件(包含扩展名的目录,包括manifest.json file)并使用DesiredCapabilities加载。可以使用

     from selenium.webdriver.chrome.options import Options

     executable_path = "path_to_webdriver"
     os.environ["webdriver.chrome.driver"] = executable_path

     chrome_options = Options()
     chrome_options.add_extension('path_to_extension')

     driver = webdriver.Chrome(executable_path=executable_path,chrome_options=chrome_options)
     driver.get("http://stackoverflow.com")
     driver.quit()

相关问题 更多 >