元素不可见:元素当前不可见,可能无法操作 - Selenium webdriver

时间:2014-09-05 06:23:43

标签: selenium

以下是html

<div id="form1:customertype" class="ui-selectonemenu ui-widget ui-state-default ui-corner-all ui-state-hover" style="width: 165px;">
   <div class="ui-helper-hidden-accessible">
      <select id="form1:customertype_input" name="form1:customertype_input" tabindex="-1">
         <option value="S">Staff</option>
         <option value="C">Customer</option>
         <option value="N">New To Bank</option></select></div>
  <div class="ui-helper-hidden-accessible"><input id="form1:customertype_focus" name="form1:customertype_focus" type="text" readonly="readonly"></div>
  <label id="form1:customertype_label" class="ui-selectonemenu-label ui-inputfield ui-corner-all" style="width: 149px;">Staff</label>
  <div class="ui-selectonemenu-trigger ui-state-default ui-corner-right ui-state-hover"><span class="ui-icon ui-icon-triangle-1-s ui-c"></span></div></div>

class =&#34; ui-helper-hidden-accessible&#34;的样式表是

ui-helper-hidden-accessible {
      border: 0;
      clip: rect(0 0 0 0);
      height: 0px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 0px;
   }

以下是我的代码

    WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
    Select select = new Select(customerType);
    select.selectByVisibleText("New To Bank");

当我尝试选择&#34; New to Bank&#34;从下拉列表中我得到例外 元素不可见:元素当前不可见,可能无法操作 - Selenium webdriver

我尝试过WebDriverWait技术但没有用,有什么想法吗?

5 个答案:

答案 0 :(得分:1)

在您尝试选择该选项之前,我并不相信该选项的文本实际可见。请尝试按值选择。

WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
Select select = new Select(customerType);
select.selectByValue("N");

但是,您可能需要实际单击选择器才能选择选项。

WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
new WebDriverWait(driver, 15).until(
            ExpectedConditions.elementToBeClickable(customerType));
customerType.click();

Select select = new Select(customerType);
select.selectByValue("N");

答案 1 :(得分:0)

在创建选择

的对象之前尝试执行点击 customerType

答案 2 :(得分:0)

好吧,我找到了解决问题的方法,但我对此并不满意。无论如何我做的是专注于div元素,通过点击它来控制下拉列表,然后向下发送两次箭头键,然后输入键。这会选择我想要的选项。我使用了以下方法

driver.switchTo().activeElement()

答案 3 :(得分:0)

我也遇到了同样的问题,几个小时后我意识到浏览器在页面加载之前试图点击一个元素。

所以我创建一个睡眠来解决问题:

sleep(1)

P.S。 - 这是一个我真的不喜欢的解决方案。 我只是告诉你原因。 您可以做的最好的事情是检查您遇到问题的页面并尝试优化加载时间。

答案 4 :(得分:0)

我遇到了同样的问题。我尝试了很多方法。
最后,以下python代码解决了该错误。
在选择选项之前,我使用javascript代码使该元素可见。

css = 'select#state' # css selector of the element
js = """const data_options = Array.from(document.querySelectorAll('{css}'));
        data_options.forEach(a=>{{a.style='display:block;';}});""".format(css=css)
self.driver.execute_script(js)

也许对您有帮助!