元素当前不可见,因此可能无法与之交互

时间:2015-02-12 23:37:33

标签: selenium selenium-webdriver

我需要选择列表中的最后一项。我的下面的代码显示了元素当前不可见的消息。怎么解决这个问题?

WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#s2id_autogen1 > a.select2-choice > span")));
WebElement element = driver.findElement(By.xpath("//select[@name='siteKey']"));
element.click();

Select select = new Select(element);
select.selectByIndex(select.getOptions().size()-1);

HTML:

<div id="overview_form">
<ol>
    <li>
        <span>1.</span>
        <label class="input_label" for="sites">Sites*</label>
        <div class="select2-container select2-dropdown-open select2-container-active" id="s2id_autogen1" style="width: 500px;">
            <a tabindex="-1" class="select2-choice" onclick="return false;" href="javascript:void(0)">   
                <span>gn</span><abbr style="display:none;" class="select2-search-choice-close"></abbr><div><b></b></div></a>
                <input type="text" class="select2-focusser select2-offscreen" disabled="disabled"></div>
        <select style="width:500px; *width:400px;" size="1" name="siteKey" class="select2-offscreen" tabindex="-1">
        <option value="30706">gn</option>
        <option value="30813">www.walmart.com_20150212151258</option>
        <option value="30815">www.walmart.com_20150212151452</option>
        <option value="30817">www.walmart.com_20150212152338</option>
        <option value="30819">www.walmart.com_20150212152521</option>
        <option value="30820">www.walmart.com_20150212152849</option>
        <option value="30822">www.walmart.com_20150212152939</option>
        <option value="30824">www.walmart.com_20150212153438</option>
        <option value="30761">www.yup.com</option>
        </select>

    </li>

</ol>

列表的屏幕截图。此列表有一个搜索字段,用户可以在其中输入前缀以缩小搜索范围。

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个。请确保根据需要展开列表。选择器以这样的方式编写,以便始终精确选择名为siteKey的选择标记的最后一个选项

//this selector find the last child o
By cssSelector = By.cssSelector("[name='siteKey']>option:last-child");

//explicit wait to make sure the element present
WebElement element = new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(cssSelector));
element.click();

System.out.println(element.getText());

打印

www.yup.com
相关问题