关闭Selenium Python中的浏览器弹出窗口

时间:2018-10-01 20:57:02

标签: python selenium selenium-webdriver webdriver webdriverwait

我正在使用Selenium和Python抓取页面。打开页面后,将显示一个弹出窗口。我还是要关闭此弹出窗口。我尝试如下:

url = https://shopping.rochebros.com/shop/categories/37

browser = webdriver.Chrome(executable_path=chromedriver, options=options)
browser.get(url)
browser.find_element_by_xpath("//button[@class='click' and @id='shopping-selector-parent-process-modal-close-click']").click()

我在这里尝试了几次类似的帖子,但没有任何帮助。在错误下方,我得到了。

 Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='click' and @id='shopping-selector-parent-process-modal-close-click']"}

2 个答案:

答案 0 :(得分:2)

所需元素是模态对话框中的<button>标签,因此要单击所需元素,需要为元素引入 WebDriverWait 可以点击,您可以使用以下解决方案:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("https://shopping.rochebros.com/shop/categories/37")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='close' and @id='shopping-selector-parent-process-modal-close-click']"))).click()

答案 1 :(得分:1)

您应该等待弹出窗口将其关闭:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

url = "https://shopping.rochebros.com/shop/categories/37"

browser = webdriver.Chrome(executable_path=chromedriver, options=options)
browser.get(url)
wait(browser, 10).until(EC.element_to_be_clickable((By.ID, "shopping-selector-parent-process-modal-close-click"))).click()

如果可能不会出现弹出窗口,则可以使用try / except继续操作,如果10秒钟内没有弹出窗口显示

from selenium.common.exceptions import TimeoutException 

try:
    wait(browser, 10).until(EC.element_to_be_clickable((By.ID, "shopping-selector-parent-process-modal-close-click"))).click()
except TimeoutException:
    print("No popup...")