【问题标题】:Python Selenium: Unable to locate the element by XpathPython Selenium:无法通过 Xpath 定位元素
【发布时间】:2019-10-13 04:42:22
【问题描述】:

我正在尝试通过 selenium 单击保存按钮,但是,我收到无法找到元素的错误。

this is the html part of the website

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("xxx")

WebDriverWait(driver,10).until(EC.presence_of_element_located(driver.find_element_by_id("DivFlashViewerMain_SavePdfButtonIcon")))
driver.find_element_by_xpath('//*[@id="DivFlashViewerMain_SavePdfButtonIcon"]').click()

这是我得到的错误:

NoSuchElementException:没有这样的元素:无法找到元素: {"method":"id","selector":"DivFlashViewerMain_SavePdfButtonIcon"}
(会话信息:chrome=74.0.3729.169)(驱动程序信息: 铬驱动程序=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

【问题讨论】:

    标签: python selenium


    【解决方案1】:
    driver.find_elements_by_css_selector('[id="DivFlashViewerMain_SavePdfButtonIcon"]')[0].click()
    

    似乎您正在使用很多功能,例如定位 id=""。强烈推荐尝试 css-selectors: How to use querySelectorAll only for elements that have a specific attribute set?

    【讨论】:

    • 强烈推荐使用 CSS 选择器......但我认为 OP 的问题在于等待 presence_of_element_located 以任何方式 +1! ;)
    【解决方案2】:

    您应该使用element_to_be_clickable 而不仅仅是presence_of_element_located

    它应该看起来像这样:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome()
    driver.get("xxx")
    
    button = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID, "DivFlashViewerMain_SavePdfButtonIcon")))
    button.click()
    

    希望这会有所帮助!

    【讨论】:

    • 这应该钉住 OP。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多