簡體   English   中英

Python和Selenium以“execute_script”來解決“ElementNotVisibleException”

[英]Python and Selenium To “execute_script” to solve “ElementNotVisibleException”

我正在使用Selenium來保存網頁。 單擊某些復選框后,網頁內容將發生變化。 我想要的是單擊一個復選框,然后保存頁面內容。 (復選框由JavaScript控制。)

首先我用過:

driver.find_element_by_name("keywords_here").click()

它以錯誤結束:

NoSuchElementException

然后我嘗試使用“xpath”,使用隱式/顯式等待:

URL = “the url”

verificationErrors = []
accept_next_alert = True

aaa = driver.get(URL)
driver.maximize_window()
WebDriverWait(driver, 10)

#driver.find_element_by_xpath(".//*[contains(text(), ' keywords_here')]").click()
#Or: 

driver.find_element_by_xpath("//label[contains(text(),' keywords_here')]/../input[@type='checkbox']").click()

它給出了一個錯誤:

ElementNotVisibleException

帖子

如何強制Selenium WebDriver點擊當前不可見的元素?

Selenium元素不可見異常

建議它應該在點擊之前使復選框可見,例如使用:

execute_script

這個問題可能聽起來很愚蠢,但是如何從頁面源代碼中找到“execute_script”復選框可見性的正確句子?

除此之外,還有另一種方式嗎?

謝謝。

順便說一句,行html代碼看起來像:

<input type="checkbox" onclick="ComponentArt_HandleCheck(this,'p3',11);" name="keywords_here">

它的xpath看起來像:

//*[@id="TreeView1_item_11"]/tbody/tr/td[3]/input

替代選項是使execute_script()內的click() execute_script()

# wait for element to become present
wait = WebDriverWait(driver, 10)
checkbox = wait.until(EC.presence_of_element_located((By.NAME, "keywords_here")))

driver.execute_script("arguments[0].click();", checkbox)

EC導入的位置為:

from selenium.webdriver.support import expected_conditions as EC

或者,作為黑暗中的另一個鏡頭,您可以使用element_to_be_clickable預期條件並以通常方式執行單擊:

wait = WebDriverWait(driver, 10)
checkbox = wait.until(EC.element_to_be_clickable((By.NAME, "keywords_here")))

checkbox.click()

我有一些預期條件的問題,我更喜歡建立自己的超時。

import time
from selenium import webdriver
from selenium.common.exceptions import \
    NoSuchElementException, \
    WebDriverException
from selenium.webdriver.common.by import By

b = webdriver.Firefox()
url = 'the url'
b.get(url)
locator_type = By.XPATH
locator = "//label[contains(text(),' keywords_here')]/../input[@type='checkbox']"
timeout = 10
success = False
wait_until = time.time() + timeout
while wait_until < time.time():
    try:
        element = b.find_element(locator_type, locator)
        assert element.is_displayed()
        assert element.is_enabled()
        element.click()
        success = True
        break
    except (NoSuchElementException, AssertionError, WebDriverException):
        pass
if not success:
    error_message = 'Failed to click the thing!'
    print(error_message)

可能想要添加InvalidElementStateException和StaleElementReferenceException

暫無
暫無

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

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