如何使用 python-selenium 在弹出 window 中单击按钮

How to click button in pop up window using python-selenium

我正在努力使无法关闭弹出窗口的网页自动化。我已经尝试 refresh/switch 弹出 window,但没有任何效果。

代码:

from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path='F:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.libertymutual.com/get-a-quote')
driver.maximize_window()
driver.find_element_by_xpath(
    '//*[@id="1555468516747"]/section/div[2]/section/form/div[1]/div[3]/div/div[1]').click()
time.sleep(1)
driver.find_element_by_xpath('//*[@id="zipcode-1555468516747-1555468516747"]').click()
driver.find_element_by_xpath('//*[@id="zipcode-1555468516747-1555468516747"]').send_keys('03878')
time.sleep(1)
driver.find_element_by_xpath(
    '//*[@id="1555468516747"]/section/div[2]/section/form/div[2]/div[5]/div/div/button').submit()
time.sleep(5)
x=driver.find_element_by_xpath('//*[@id="discount-marketing-modal"]/header/button/svg').click()
driver.refresh()

如果您想直接进入网页,https://buy.libertymutual.com/auto?city=Somersworth&jurisdiction=NH&lob=Auto&policyType=Auto&zipCode=03878

将代码的最后 3 行替换为下面的 lines.Used 要点击的操作链。

time.sleep(5)
ok =  driver.find_element_by_xpath('//*[@id="discount-marketing-modal"]/footer/button')
ActionChains(driver).move_to_element(ok).pause(1).click(ok).perform()
x=driver.find_element_by_xpath('//*[@id="discount-marketing-modal"]/header/button/svg').click()

这是弹出关闭按钮的 css 选择器:.lm-Icon.lm-Icon-Close

但是这个元素不能使用.click()方法,.click()方法会产生这个错误:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted:

使用ActionChains解决这个问题。

您可以试试下面的代码:

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

driver = webdriver.Chrome(executable_path='F:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.libertymutual.com/get-a-quote')
driver.maximize_window()

wait = WebDriverWait(driver, 20)
auto_element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='quotingText']//span[contains(text(), 'Auto')]")))
auto_element.click()
zip_code = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.zipcode")))
zip_code.click()
zip_code.send_keys("03878")
driver.find_element_by_css_selector('div.buttonWrapper button').submit()
popup_close_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".lm-Icon.lm-Icon-Close")))
action = ActionChains(driver)
action.move_to_element(popup_close_btn).click(popup_close_btn).perform()

WebDriverWait 优于 time.sleep(..)