![](/img/trans.png)
[英]How can I locate an element using selenium 2 which do not have unique identifiers like Name, Id
[英]How to Select Dropdown which does not have a Name or ID in Selenium
我無法選擇沒有相關屬性的下拉菜單。 在HTML代碼下方,可以看到沒有選擇標記,但沒有ID或名稱。 如何在Selenium中選擇該標簽?
<!DOCTYPE html>
<html>
<body>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
以下是該下拉菜單所在的網站。 網站: https : //www.w3schools.com/tags/tryit.asp?filename=tryhtml_select
我已經嘗試從文檔的根目錄開始,跟隨兄弟等等,但是沒有任何結果。 我得到了意外成功
這就是原因,我在這里發布一個問題。
以下是我的代碼,
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class X
{
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
WebElement element= driver.findElement(By.xpath("/html/body/select"));
Select s = new Select(element);
s.selectByValue("saab");
}
}
實際上,這里的問題是,您的元素位於iFrame
因此首先您需要在頁面中找到正確的iFrame
即名稱為iframeResult
並切換到其中。
然后,您可以使用標記名本身找到相同的下拉列表:使用以下代碼,讓我知道是否存在任何問題
driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.switchTo().frame("iframeResult");
WebElement element = driver.findElement(By.tagName("select"));
Select select = new Select(element);
select.selectByIndex(1);
首先,單擊您的元素以展開下拉列表:
s.click()
接下來嘗試以下方法之一:
s.selectByValue("saab")
s.selectByVisibleText("saab")
s.selectByIndex(1)
您的代碼是正確的一半,首先您必須切換到框架,然后嘗試從下拉列表中選擇值。 您的正確代碼應如下所示:
public class X
{
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.switchTo().frame("iframeResult");
WebElement dropdownBrands = driver.findElement(By.xpath("/html/body/select"));
Select s = new Select(dropdownBrands);
s.selectByVisibleText("Saab");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.