【问题标题】:Close browser popup in Selenium Python在 Selenium Python 中关闭浏览器弹出窗口
【发布时间】:2018-10-01 20:57:02
【问题描述】:

我正在使用 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']"}

【问题讨论】:

    标签: python selenium selenium-webdriver webdriver webdriverwait


    【解决方案1】:

    所需的元素是 Modal Dialog 中的 <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()
    

    【讨论】:

      【解决方案2】:

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

      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...")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多