簡體   English   中英

找到Python Selenium Webdriver元素,但無法單擊它

[英]Python Selenium Webdriver element found but can not click on it

目標是單擊登錄頁面上的復選框。 我通過XPATH找到了元素,但是無法單擊它。

>>> elem = driver.find_element_by_xpath("//input[@type='checkbox'][@name='conditions']")
>>> elem.is_displayed()
False
>>> elem.is_enabled()
True
>>> elem.get_attribute('outerHTML')
u'<input type="checkbox" class="custom-control-input" name="conditions">'

當我嘗試elem.click() ,發生異常: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible但元素清晰可見,因為頁面已加載並且我從終端工作。

使用其他選擇器時的其他錯誤是: driver.find_element_by_xpath('/html/body/div[2]/main/section/div/div[3]/div/div[1]/form/p[1]/label/input').click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <input type="checkbox" class="custom-control-input" name="conditions"> is not clickable at point (51, 549). Other element would receive the click: <span class="custom-control-description font-weight-regular">...</span>

我嘗試注入JavaScript,但是沒有用。 driver.execute_script("arguments[0].style.visibility = 'visible';",elem)

任何想法如何解決這個問題?

您可以使用此XPATH:- //input[@type='checkbox'and @name='conditions']

對於以下錯誤:-使用點擊事件之前等待

selenium.common.exceptions.WebDriverException:消息:未知錯誤:元素在點(51,549)不可單擊。 其他元素將獲得點擊:...

根據您嘗試時的代碼試用:

elem.click()

您正在看到:

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

這意味着所需元素在HTML DOM中仍然不可見

甚至在嘗試點擊之前,也可以:

elem.is_displayed()

您正在看到:

False

但是當您嘗試:

elem.is_enabled()

您正在看到:

True

因此,結合所有這些觀察結果,可能是以下兩種情況之一:

  • 元素存在DOM中,但仍然不可見/不可交互。 在這種情況下,您需要引入WebDriverWait ,然后click()如下所示調用click()

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@type='checkbox' and @name='conditions']"))).click() 
  • 元素存在DOM中,但不存在於Viewport中 在這種情況下,您需要調用execute_script()將元素放入視口中 ,然后click()如下所示調用click()

     elem = driver.find_element_by_xpath("//input[@type='checkbox' and @name='conditions']") driver.execute_script("arguments[0].scrollIntoView(true);", elem) elem.click() 
  • 您采用的“ 定位器策略”有可能不是唯一的,並且會標識多個WebElement,並且要標識的第一個元素可能會被隱藏。 在這種情況下, is_displayed()將始終返回False,並且您必須構造一個唯一的定位器策略 ,該策略可以唯一地標識預期的元素。
  • 元素的樣式屬性可能設置為顯示: 在這種情況下,您必須使用execute_script()方法,如下所示:

     elem = driver.find_element_by_xpath("//input[@type='checkbox' and @name='conditions']") driver.execute_script("arguments[0].removeAttribute('style')", elem) elem.click() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM