Selenium (python):如何检测并单击模态错误中的“确定”按钮 window

Selenium (python): How to detect and click on the Ok button within a modal error window

当在以下网站上搜索失败时,会打开一个小的错误模式对话框,但是我的代码找不到我在源代码中看到的“id=noresultsfound”HTML:

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

driver = webdriver.Chrome(
    "/Users/bob/Documents/work/AIFA/scraper/scrape_gu/chromedriver"
)

# navigate through the initial agreement screens
driver.get("https://farmaci.agenziafarmaco.gov.it/bancadatifarmaci/cerca-farmaco")
readunderstood = driver.find_element_by_id("conf")
readunderstood.click()
accept = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "/html/body/div[5]/div[3]/div/button"))
)
accept.click()
# end of the initial agreement screens

# now input search string
find_textbox = driver.find_element_by_id("search")
find_textbox.send_keys("ZQ")
find_textbox.send_keys(Keys.ENTER)
# check if any results found
# if not we have //*[@id="noresultsfound"]
try:
    element = WebDriverWait(driver, 5).until(
        EC.presence_of_element_located((By.ID, "noresultsfound"))
    )
finally:
    driver.quit()

当然,感兴趣的代码是#check if any results found 注释之后的代码。

当然,我还需要单击“确定”按钮将其关闭,但我猜这也是可行的,因为我能够找到模态window。

代码可以按原样运行。

确定 元素在 Modal Dialog Box. To on the clickable element need to induce WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ui-dialog-buttonset span.ui-button-text"))).click()
    
  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='ui-button-text' and text()='Ok']"))).click()
    
  • 注意:您必须添加以下导入:

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