【问题标题】:Python Selenium: Unable to find xpath to click on element within iframePython Selenium:无法找到 xpath 以单击 iframe 中的元素
【发布时间】:2022-02-04 06:57:34
【问题描述】:

我正在使用此代码,但无法使其与 xpath 一起使用:

browser = webdriver.Chrome(chrome_path)
browser.get("https://planetradio.co.uk/cool-fm")
time.sleep(5)
browser.find_element_by_xpath('//*[@id="notice"]/div[4]/button[2]').click()

【问题讨论】:

  • 你想点击哪个元素?
  • 会弹出一个按钮,上面写着“全部接受”以同意cookies,我希望上面的xpath可以工作。

标签: python selenium xpath iframe css-selectors


【解决方案1】:

元素 ACCEPT ALL<iframe> 内,因此您必须:

  • 诱导WebDriverWait 使所需的帧可用并切换到它

  • 诱导WebDriverWait 使所需的元素可点击

  • 您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR

      driver.get('https://planetradio.co.uk/cool-fm/')
      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='ACCEPT ALL']"))).click()
      
    • 使用XPATH

      driver.get('https://planetradio.co.uk/cool-fm/')
      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='ACCEPT ALL']"))).click()
      
  • 注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait
     from selenium.webdriver.common.by import By
     from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照:


参考文献

您可以在以下位置找到一些相关讨论:

【讨论】:

  • 谢谢,这很有帮助。你怎么知道按钮的 xpath 是 //button[@title='ACCEPT ALL'] 而不是 //*[@id="notice"]/div[4]/button[2]
  • @Pythonaccount 看到这个detailed discussion
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多