简体   繁体   English

使用 Selenium 选择没有 ID 的下拉值

[英]Selecting dropdown value without ID using Selenium

Got below HTMLcode for dropdown:得到下面的 HTMLcode 下拉:

<select name="PWCMasterPage$PWCWebPartManager$gwpTemplateFr1$TemplateFr1$drpProductType" id="PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType" tabindex="2" class="PWCDropDownList" profiledatamember="" profileid="TEMPLATE" onblur="this.Holder = GetControlHolder(this);" onchange="this.Holder = GetControlHolder(this);" onfocus="this.Holder = GetControlHolder(this);" data-val-subtype-type="none" controlscollectionname="TemplateFr1_drpProductType" data-configid="TemplateFr1_drpProductType" holdername="TemplateFr1Holder">
<option value=""></option>
<option value="7">Expedited</option>
<option value="8">Premier</option>
<option value="9">Value</option>
</select>

Have been trying to select the dropdown values with:一直在尝试 select 下拉值:

Select dropDown = new Select(driver.findElement(By.xpath("//*[@id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
dropDown.selectByValue("8");

Getting below error:出现以下错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Cannot locate option with value: 8线程“主”org.openqa.selenium.NoSuchElementException 中的异常:无法找到具有值的选项:8

Select dropDown = new Select(driver.findElement(By.xpath("//*[@id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
dropDown.selectByVisibleText("Expedited");

Which resulted in below error:导致以下错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Cannot locate element with text: Expedited线程“主”org.openqa.selenium.NoSuchElementException 中的异常:无法找到带有文本的元素:加急

Have tried alternately with selectByVisibleText and selectByIndex as well which resulted in similar errors.也曾尝试与 selectByVisibleText 和 selectByIndex 交替使用,这导致了类似的错误。

Are you using safari?您使用的是 safari 吗?

If so, there's known issues with webdriver and safari.如果是这样,则 webdriver 和 safari 存在已知问题。 The long and short of it is to use the driver provided by apple.它的长短是使用苹果提供的驱动程序。

This is the selenium issue: https://github.com/SeleniumHQ/selenium/issues/3145这是 selenium 问题: https://github.com/SeleniumHQ/selenium/issues/3145

If you look at: https://webkit.org/blog/6900/webdriver-support-in-safari-10/如果你看: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

They say:他们说:

"Safari's driver is launchable via the /usr/bin/safaridriver executable, and most client libraries provided by Selenium will automatically launch the driver this way without further configuration." “Safari 的驱动程序可通过/usr/bin/safaridriver可执行文件启动,Selenium 提供的大多数客户端库将自动以这种方式启动驱动程序,无需进一步配置。”

The issue isn't the java code you provided or the HTML source.问题不在于您提供的 java 代码或 HTML 源代码。

I created a simple web page with your html:我用您的 html 创建了一个简单的 web 页面:

<html><body>
<select name="PWCMasterPage$PWCWebPartManager$gwpTemplateFr1$TemplateFr1$drpProductType" id="PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType" tabindex="2" class="PWCDropDownList" profiledatamember="" profileid="TEMPLATE" onblur="this.Holder = GetControlHolder(this);" onchange="this.Holder = GetControlHolder(this);" onfocus="this.Holder = GetControlHolder(this);" data-val-subtype-type="none" controlscollectionname="TemplateFr1_drpProductType" data-configid="TemplateFr1_drpProductType" holdername="TemplateFr1Holder">
    <option value=""></option>
    <option value="7">Expedited</option>
    <option value="8">Premier</option>
    <option value="9">Value</option>
</select>
</body></html>

I created a simple test class - and it works lovely, Pasting the lot so you can see i do nothing other than open the page.我创建了一个简单的测试 class - 它工作得很好,粘贴很多所以你可以看到除了打开页面我什么都不做。 use your code and select the element.使用您的代码和 select 元素。


public class StackTest {

    private String baseUrl = "C:\\Git\\stackTest.html";
    private WebDriver driver;

    @Before
    public void CreateWebDriver()
    {
        System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get(baseUrl);
    }

    @After
    public void CloseAndQuitWebDriver() {
        driver.close();
        driver.quit();
    }

    @Test
    public void approach1_ExistingCode()
    {
        Select dropDown = new Select(driver.findElement(By.xpath("//*[@id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
        dropDown.selectByValue("8");
    }
}

In my opinion, the problem isn't selenium, the problem isn't the xpath, as long as you're doing what @SeleniumUser002 says in his answer then the problem isn't object accessibility.在我看来,问题不在于 selenium,问题不在于 xpath,只要您按照@SeleniumUser002 在他的回答中所说的进行操作,那么问题不在于 ZA8CFDE6331BD49EB62AC96F89111 的可访问性。

Have a think about:想一想:

  • What is your site doing that's special?您的网站有什么特别之处?
  • Is it doing anything script based which creates/populates this drop down at run time?它是否在执行任何基于脚本的操作,在运行时创建/填充此下拉列表?
  • When you captured the html did you capture it from chrome manually or chromedriver at runtime?当您捕获 html 时,您是在运行时手动从 chrome 捕获它还是从 chromedriver 捕获它? (try the latter if you didn't already - Running manually is what a user sees, but chromedriver is what selenium sees. Be careful not to click on anything else other than the object when inspecting so you don't skew the results) (如果您还没有尝试使用后者 - 手动运行是用户看到的,但 chromedriver 是 selenium 看到的。注意在检查时不要点击 object 以外的任何其他内容,以免影响结果)
  • Are you doing any other steps in the script that can influence this dropdown?您是否在脚本中执行任何其他可能影响此下拉列表的步骤?

First thing i would say to really fixing this issue is to use a breakpoint before your broken line and slowly step though the actions that lead the issue.要真正解决这个问题,我要说的第一件事是在断线之前使用断点,然后慢慢地逐步解决导致问题的操作。 See if the page is behaving differently at runtime.查看页面在运行时是否表现不同。 Walking through slowly also removes synchronisation issues and once the code works once, if it goes back to being flaky you can rule out the code and focus on a better wait strategy.慢慢地遍历也消除了同步问题,一旦代码工作一次,如果它回到片状,你可以排除代码并专注于更好的等待策略。

If that doesn't work and you're STILL seeing all the options present but cannot select, do a dump of what selenium can see:如果这不起作用并且您仍然看到所有选项但不能看到 select,请转储 selenium 可以看到的内容:

@Test
public void debug_WhatAreMyOptions()
    {
        Select dropDown = new Select(driver.findElement(dropdownIdentifier));
        System.out.println("dropdown has "+ dropDown.getOptions().size()+" options");

        System.out.println("the options are....");
        for (var dropdownOptions : dropDown.getOptions()) {
            System.out.println(dropdownOptions.getText());
        }

    }

That might help you actually figure out what's happening to solve the issue.这可能会帮助您真正弄清楚解决问题的方法。 Without that debugging information no one can tell you what the problem is - but i can suggest work arounds!如果没有该调试信息,没有人可以告诉您问题所在 - 但我可以建议解决方法!

Try these...试试这些...

Set this up:设置这个:

private By dropdownIdentifier = By.xpath("//*[@id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]");
    

Then try old fashioned clicks without a select object:然后尝试没有 select object 的老式点击:

public void approach2_Clicks()
    {
        driver.findElement(dropdownIdentifier ).click(); // to activate
        driver.findElement(dropdownIdentifier ).findElement(By.xpath("//*[@value='8']")).click();
    }

Or try our old friend javascript:或者试试我们的老朋友 javascript:

 public void approach3_Javascript()
    {
        var dropdown = driver.findElement(dropdownIdentifier);
        ((JavascriptExecutor) driver).executeScript("arguments[0].value='8'", dropdown);
    }

However - these work arounds are only possible if the list is populated... My gut tells me that the data isn't there to select at runtime, but as you say it's an internal link so only you can verify that:-)但是 - 这些变通办法只有在填充列表时才有可能......我的直觉告诉我在运行时 select 的数据不存在,但正如你所说的它是一个内部链接,所以只有你可以验证:-)

Give it a go and let us know.给它一个 go 并告诉我们。

try below solution with WebDriverWait to avoid synchronization issue:使用 WebDriverWait 尝试以下解决方案以避免同步问题:

    WebDriverWait wait = new WebDriverWait(driver,30);
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("PWCDropDownList")));
    Select drpCountry = new Select(element);
    drpCountry.selectByValue("8");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM