2017-06-05 59 views
0

我想用Python Selenium安装Chrome扩展。 当我点击添加到Chrome按钮时,弹出一个弹出窗口(不知道它是否是一个java脚本),询问:“添加扩展名”,“取消”。我想点击“添加扩展名”,但我收到以下错误:通过Python安装Chrome扩展时出错 - 硒

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() 

帮我安装它。

更新代码:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 
import os 

executable_path = "C:\\Users\\SACHIN\\AppData\\Local\\Programs\\Python\\Python36\\chromedriver" 
os.environ["webdriver.chrome.driver"] = executable_path 

chrome_options = Options() 
chrome_options.add_extension("C:\\Users\\SACHIN\\AppData\\Local\\Google\\chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\ 
3.4.143_0") 

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

回答

0

这是因为下载选项弹出您尝试使用switch_to.alert选择并不是一个真正的JS警报弹出。您无法选择使用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() 
+0

能否请你帮我在哪里可以找到路径延伸 –

+0

路径扩展,你会下载你的'.crx'文件的路径来完成。假设你在一个Linux系统上,它可能是/用户/下载或一些直接 – demouser123

+0

我正在使用Windows 10 –