[英]how to close chrome browser popup dialog using selenium webdriver and python
[英]Close browser popup in Selenium Python
我正在使用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']"}
所需元素是“ 模态对话框”中的<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()
您应该等待弹出窗口将其关闭:
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...")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.