Selenium - 无法点击隐藏元素

时间:2016-11-29 20:38:24

标签: python selenium selenium-webdriver automated-tests

我正在使用Selenium和Python。我正在努力使用click()方法来单击动态创建的单选按钮。收音机的标记在下面。

<input version="2" value="1" class="linked-ftb-radio meta(controlNumber=2)" id="radio_1" name="IndexString" reference="TEST 01" type="radio">
<label for="radio_1" id="linked-label" class="radio-label"></label>

我的代码是:

driver.find_element_by_xpath('//*[@id="radio_1"]').click()

但是会产生以下错误:

Traceback (most recent call last):
  File "index.py", line 41, in <module>
    driver.find_element_by_xpath('//*[@id="radio_1"]').click()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 74, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 457, in _execute
    return self._parent.execute(command, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with

当按下标签时,通过更改图像来模拟收音机。换句话说,点击时,课程会更改为radio-label selected

radio

如何点击Selenium的单选按钮,记住它目前不可见?

2 个答案:

答案 0 :(得分:1)

尝试explicit condition等待元素显示。 (如果是与时间有关的问题,即需要时间来显示)

 element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, "//*[@id='radio_1']"))
 element.click()
  

在抛出TimeoutException之前等待最多10秒,或者如果它出现在页面的DOM上并且可见,将在0-10秒内返回。默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到它成功返回。成功返回的是ExpectedCondition类型是布尔返回true或非null返回值,用于所有其他ExpectedCondition类型。

参考:

  1. https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.visibility_of_element_located
  2. http://selenium-python.readthedocs.io/waits.html

答案 1 :(得分:1)

<强> C#

您可以使用服务员元素来显示如下:

var element = Waiter.Until(ExpectedConditions.ElementIsVisible(By.Id("ID"))).FirstOrDefault();