簡體   English   中英

Selenium WebDriver:如何在范圍下拉列表中選擇一個值?

[英]Selenium WebDriver: How to select a value in a span dropdown?

我正在嘗試讓我的Selenium腳本在下拉菜單中單擊一個值。 但是,我最初單擊它后,無法在下拉菜單中進行任何操作。 我在網上看過,並且只有下拉菜單為“選擇”時才能找到答案。

這是下拉菜單的HTML:

<span class="select2-selection__rendered" title="1st item"
      id="select2-id_template_or_inspection-container">
</span>

這是我單擊下拉列表的代碼片段:

//Choose a Template from Dropdown

WebElement dropdownBtn = webDriver.findElement(
            By.id("select2-id_template_or_inspection-container"));

dropdownBtn.click();

這是我嘗試單擊下拉列表中的值的代碼段:

WebElement dropdownItemBtn = webDriver
      .findElement(By.id("select2-id_template_or_inspection-result-hlwt-tmpl-2583"));
dropdownItemBtn.click();

但是,每次重新加載頁面時,下拉列表中值的ID都會更改。

感謝您的幫助!

您可以嘗試以下方法:

  1. 這就是您要做的,單擊跨度以顯示其下拉項

     //Choose a Template from Dropdown WebElement dropdownBtn = webDriver.findElement(By.id("select2-id_template_or_inspection-container")); dropdownBtn.click(); 
  2. 由於每次重新加載頁面時下拉列表中值的ID都會更改,因此您可以使用dropdownBtn查找其子項作為下拉項,然后單擊所需的下拉菜單:

     List<WebElement> dropdownItems = dropdownBtn.findElements(By.tagName("tagNameOfDropdownItems")); dropdownItems.get(0).click(); // click on first Dropdown, for example 

因為ID是動態更改的,所以讓我們嘗試通過tagName查找元素。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM