Python and Selenium To “execute_script” to solve “ElementNot



我使用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点击当前不可见的元素?

硒元素不可见异常

建议在单击前使复选框可见,例如:

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

另一种选择是将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() # or if you really want to use an execute script for it, you can do that here.
        success = True
        break
    except (NoSuchElementException, AssertionError, WebDriverException):
        pass
if not success:
    error_message = 'Failed to click the thing!'
    print(error_message)

可能需要添加InvalidElementStateException和StaleElementReferenceException

最新更新