简体   繁体   English

无法使用 CssSelector 和 Selenium 单击元素 Python

[英]Unable to click on an element using CssSelector and Selenium Python

I open this site in python https://zeitung.faz.net/ when open a message in popup this site我在 python https://zeitung.faz.net/打开这个网站时在弹出这个网站的消息

driver.find_element_by_css_selector("#notice > div.message-component.message-row.sticky-element > div.message-component.message-row.row-no-margin-phone.cta-yep > div").click()

but not work但不工作

The element ZUSTIMMEN is within an <iframe> so you have to: ZUSTIMMEN元素位于<iframe>中,因此您必须:

  • Induce WebDriverWait for the desired frame to be available and switch to it .诱导WebDriverWait以等待所需的框架可用并切换到它

  • Induce WebDriverWait for the desired element to be clickable .诱导WebDriverWait使所需的元素可点击

  • You can use either of the following Locator Strategies :您可以使用以下任一定位器策略

    • Using CSS_SELECTOR :使用CSS_SELECTOR

       driver.get('https://zeitung.faz.net/') WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='SP Consent Message']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='ZUSTIMMEN']"))).click()
    • Using XPATH :使用XPATH

       driver.get('https://zeitung.faz.net/') WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='SP Consent Message']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='ZUSTIMMEN']"))).click()
  • Note : You have to add the following imports:注意:您必须添加以下导入:

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

Reference参考

You can find a couple of relevant discussions in:您可以在以下位置找到几个相关的讨论:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM