Python和Selenium以“execute_script”来解决“ElementNotVisibleException”

时间:2015-07-14 04:07:42

标签: javascript python selenium selenium-webdriver

我正在使用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

帖子

How to force Selenium WebDriver to click on element which is not currently visible?

Selenium Element not visible exception

建议在点击之前使复选框可见,例如使用:

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

2 个答案:

答案 0 :(得分:6)

替代选项是在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()

答案 1 :(得分:1)

我在预期条件上有一些问题,我更喜欢建立自己的超时时间。

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