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

标签 reactjs selenium xpath automation

您好,需要使用 By.xpath() 选择“新南威尔士州”,有什么建议吗?

这是一个reactjs页面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)

最佳答案

请按照以下步骤选择您想要的元素

  1. 点击下拉菜单的向下箭头
  2. 选择所需的选项

这是相同的代码:

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();
}

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

例如

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

关于reactjs - 使用 Selenium 从输入组合框中选择一个值,使用 xpath 作为reachjs 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668983/

相关文章:

javascript - 在 React 中初始化和使用 `sessionStorage`

reactjs - 从 Ant Design Table 获取当前表数据

reactjs - 使用 React Children 代码示例不起作用

java - 有没有办法通过跨度内容点击 <span> 标签

C# Selenium 循环遍历 Span 类 XPATH 中的输入按钮

php - 空白 "DOMNodeList"通过 Xpath 读取 XML

javascript - 构建依赖于第三方脚本的组件

design-patterns - Selenium WebDriver 中的页面对象模式是什么?

python - 在 Python 2.7 上使用 xpath 提取 href 值

sql - 从 Oracle 数据库中的 XML 属性查询时如何使用 XPath 表达式