使用selenium为javascript下拉选择自动化

时间:2014-10-17 06:59:01

标签: java javascript selenium selenium-webdriver

我需要从下拉列表中选择一个值,该值包含javascript。任何帮助都非常感谢!

关注HTML:

<div class="popupMenuButton">
    <a id="_sawrl" bh="PML" _mid="_g7yog" class="awmenuLink" style="text-decoration:none" href="#">
        <nobr>
            FORMALIN VAPO TABS
            <img width="15" height="17" align="absmiddle" border="0" style="margin-bottom:1px;" src="/EasyCare-2.0/AribaWeb/ad/content/AWXDebugResourceActions/13/en_US/widg/arrowcolor.gif" alt="">
        </nobr>
    </a>
</div>

Java代码

WebElement dropDownListBox = waitById("_sawrl");
Select clickThis = new Select(dropDownListBox);
clickThis.selectByVisibleText("FORMALIN VAPO TABS")

异常

Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a"
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: , os.name: 'Windows 8', os.arch: 'x86', os.version: '6.2', java.version: '1.7.0_51'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.Select.<init>(Select.java:46)
    at ui.stores.UIMaterialRecepit.setBrandName(UIMaterialRecepit.java:71)
    at tc.stores.TCMaterialRecepit.receiveMaterial(TCMaterialRecepit.java:32)
    at tc.StartAutmation.main(StartAutmation.java:48)

3 个答案:

答案 0 :(得分:1)

正如例外所说:

  

Element should have been "select" but was "a"

您的dropDownListBox是一个锚元素。 (<a id="_sawrl"...)。
new Select()仅接受<select>元素。

答案 1 :(得分:0)

正如Cerbrus所说,你的元素不是真正的选择。你可以通过点击来处理这些东西。

说,你的选择&#39;看起来像:

<div class="menubox-select AFGFLKJV">
    <div class="menuItem" row="1" >Info</div>
    <div class="menuItem" row="2" >Stuff</div>
    <div class="menuItem" row="3" >Teddy Bears</div>
</div>

然后,为了选择:

driver.findElement(By.xpath("//div[contains(@class, 'menubox-select')]").findElement(By.xpath(".//*[contains(text(), 'Stuff')]").click();

对于自定义选择框来说,这是很平常的事情。但是,您可以省略使用element.findElement。在点击选项之前,您需要触发可见的选项,否则您将获得例外。

答案 2 :(得分:0)

我能够找出问题所在。谢谢@Cerbrus和@TEH的指点。

以下是java代码:

driver.findElement(By.xpath("//*[@id='_sawrl']").click();
driver.findElement(By.xpath("//*[@id='_immwib']").click();