java - 在 Selenium 中选择下拉值的方法

标签 java selenium selenium-webdriver

我需要一个简单的方法将值发送到“dropID

值为

阿联酋、巴林、阿曼...等

下拉用户界面

enter image description here

我的 xpath(全局)

//*[@id="wrapper"]/div[1]/header/div[2]/div[2]/div[1]/div[1]/div[2]/nav/ul/li[' + **dropID** + ']/a

HTML

<nav class="header__countries-menu--desktop mi-js-countries-menu-desktop" style="display: block;">
                  <ul>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=ae&amp;url=/Sponsored">UAE</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=bh&amp;url=/Sponsored">Bahrain</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=om&amp;url=/Sponsored">Oman</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=qa&amp;url=/Sponsored">Qatar</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=kw&amp;url=/Sponsored">Kuwait</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=eg&amp;url=/Sponsored">Egypt</a>
                    </li>
                    <li class="header__country-selector--desktop__country">
                      <a href="/change-country?to=jo&amp;url=/Sponsored">Jordan</a>

我对 Selenium 很陌生,正在寻求帮助

最佳答案

(1) 不要使用绝对路径,这是不好的做法。请参阅下面的一些动态 xpath 示例:

假设您的 CountryPage 类下有此内容

WebElementcountryEle = driver.findElement(By.xpath("//[@class='header__countries-menu--desktop mi-js-countries-menu-desktop']//[包含(text(),'"+dynamicText+"')]") ;

WebElementcountryEle = driver.findElement(By.xpath("//[@class='header__country-selector--desktop__country']//[contains(text(),'"+dynamicText+ “')]”);​​

(2) 您需要点击下拉菜单才能点击任何国家/地区:

driver.findElement(By.xpath("dropDown of your country ")).click();

(3) 将您的动态 DropID 发送到选择的国家/地区:

public static void selectFromDropdown(WebDriver driver, WebElement element)
{
    driver.findElement(element).click();
}

(4) 调用你的方法:

selectFromDropdown(driver,CountryPage(driver,"UAE"))

关于java - 在 Selenium 中选择下拉值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071735/

相关文章:

java - 列出 JRE 上的 Java 虚拟机

java - 如何返回到另一个案例

java - 范围报告report.endTest(test)方法?

java - 如何使用 selenium webdriver 从列表框中移动项目

java - 将 ExplicitWait 方法调用到功能特性中

java - 一旦我运行一个自动化测试场景,有没有一种方法可以使用自动化测试场景本身来检查 Linux 服务器日志错误消息和异常

java - 类型为 numberDecimal 的 EditText 不允许以 0 开头的值

java - 如何将项目动态添加到 Java 数组?

java - 使用 Selenium 放大和缩小

java - Selenium : How to retrieve WebDriver's implicitWait time in Java?