使用Selenium从输入组合框中选择一个值,使用xpath作为reachjs控件

时间:2017-08-14 06:57:51

标签: reactjs selenium xpath automation

您需要选择"新南威尔士"请使用By.xpath()任何建议吗?

这是反应页面jedwatson.github.io/react-select

<div class="Select-control">
    <span class="Select-multi-value-wrapper" id="react-select-2--value">
        <div class="Select-value State-NSW">
            <span class="Select-value-label" role="option" aria-selected="true" id="react-select-2--value-item">New South Wales</span>
        </div>
        <div class="Select-input" style="display: inline-block;">
            <input role="combobox" aria-expanded="false" aria-owns="" aria-haspopup="false" aria-activedescendant="react-select-2--value" value="" style="width: 5px; box-sizing: content-box;">
            <div style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-size: 14px; font-family: &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; font-weight: normal; font-style: normal; letter-spacing: normal;"></div>
        </div>
    </span>
    <span class="Select-clear-zone" title="Clear value" aria-label="Clear value">
        <span class="Select-clear">×</span>
    </span>
    <span class="Select-arrow-zone">
        <span class="Select-arrow"></span>
    </span>
</div>

尝试使用以下代码但未成功

driver.findElement(By.xpath("//input[@role='combobox'][@value='New York"']")).click();;

观察到以下异常

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@role='combobox'][@value='New York']"}
  (Session info: chrome=59.0.3071.86)

2 个答案:

答案 0 :(得分:2)

请按照以下步骤选择所需的元素

  1. 点击下拉列表中的向下箭头
  2. 选择所需选项
  3. 以下是相同的代码:

    driver.findElement(By.xpath("//h3[contains(text(),'States')]/..//span[@class='Select-arrow']")).click();
    driver.findElement(By.id("react-select-2--option-1")).click();
    

    <强>更新

    使用以下方法根据文本动态选择值:

    public void selectCombo(String valueText)
    {
        driver.findElement(By.xpath("//h3[contains(text(),'States')]/..//span[@class='Select-arrow']")).click();
        WebElement dropdownValue = driver.findElement(By.xpath("//div[contains(text(),'"+valueText+"')]"));
        dropdownValue.click();
    }
    

    从您的代码中调用此方法并传递您要选择的值

    e.g。

    new TestClass().selectCombo("Tasmania");
    

答案 1 :(得分:0)

您可以尝试使用xpath //*[@role="option" and text()='New South Wales']