首页 > 解决方案 > Selenium Webdriver 找不到点击按钮的元素

问题描述

我不知道用于单击按钮的元素。

我试着这样写:

driver.find_element_by_xpath('//*/input[@type="button"]').click()

错误信息:

raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

HTML:

<input type="button" name="ctl00$c3$g_6_f947_400a_aa18_59efd84584ae$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem" value="Save" onclick="if (!PreSaveItem()) return false;if (SPClientForms.ClientFormManager.SubmitClientForm('WPQ2')) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ctl33$g_69_f947_400a_aa18_59efd84584ae$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))" id="ctl00_ctl33_g_696_f947_400a_aa18_59efd84584ae_ct0_toolBarTbl_RightRptControls_ctl00_ctl00_diidIOSaveItem" accesskey="O" class="ms-ButtonHeightWidth" target="_self">

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


所需的元素是动态元素,因此要定位元素,您必须诱导WebDriverWait以使元素可点击,您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ms-ButtonHeightWidth[value='Save'][name$='SaveItem']"))).click()
    
  • 使用XPATH

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ms-ButtonHeightWidth' and @value='Save'][contains(@name, 'SaveItem')]"))).click()
    
  • 注意:您必须添加以下导入:

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

推荐阅读