1

我使用Selenium + Eclipse。我需要從下拉菜單中選擇項目,但是我遇到了問題,也許無法找到元素。我的代碼如下:我無法通過Selenium Webdriver從下拉菜單中選擇

package firstTC; 
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.support.ui.Select; 
import org.openqa.selenium.chrome.ChromeDriver;; 

public class Testcase { 


    public static void main(String[] args) { 
     System.setProperty("webdriver.chrome.driver", "C:\\Users\\nazar\\Desktop\\New folder\\chromedriver.exe"); 
     ChromeDriver driver = new ChromeDriver(); 
     driver.get("https://www.goindigo.in/"); 
     driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='roundWay']/form/div[1]/ul[1]/li[1]/input[1]"))); 
     oSelect.selectByIndex(3); 

    } 

} 

我試過不同的定位器,但它沒有幫助。

+1

'也許元素無法找到... ...也許?你希望我們猜測你的代碼有什麼問題? – Andersson

+0

請參閱[如何提問](http://stackoverflow.com/help/how-to-ask)。更具體地說,請提供發生情況的描述,是否會出現錯誤?如果是這樣,那是什麼?另外,請提供相關的html。謝謝! – mrfreester

回答

1

你在找什麼不是「下拉式」。試着點擊它起初:

driver.findElement(By.xpath(".//*[@id='roundWay']/form/div[1]/ul[1]/li[1]/input[1]")).click(); 

,然後點擊子菜單:

driver.findElement(By.xpath(".//li[@data-val='IXA']")).click(); 
0

我一直GoIndigo網站,並試圖檢查你所提到的XPath的你碼。 這是在你的代碼中提到的XPath是「從」字段(糾正我,如果我錯了),這是一個文本(不是下拉

所以,與其

Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='roundWay']/form/div[1]/ul[1]/li[1]/input[1]"))); 
     oSelect.selectByIndex(3); 

應該使用

driver.findElement(By.xpath(".//*[@id='roundWay']/form/div[1]/ul[1]/li[1]/input[1]").sendKeys("something"); 
0

試試這個下面的代碼:

driver.get("https://www.goindigo.in/"); 
driver.manage().window().maximize(); 
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
driver.findElement(By.xpath("//input[@placeholder='From']")).click(); 
WebDriverWait wait = new WebDriverWait(driver, 15); 
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//li[@data-val='BLR']")))); 
driver.findElement(By.xpath("//li[@data-val='BLR']")).click(); 

說明:使用XPath定位From元素首先點擊,然後等到要點擊它的元素。對於wait我使用Explicit wait方法。

在這裏,在我的例子中,我想點擊Bengaluru,所以根據Bengaluru,我已經爲Bengaluru城市創建了一個xpath。

如果你想點擊其他城市而不是Bengaluru那麼你必須爲該城市編寫適當的xpath。

0

你試圖使用Select類的方式,它不是那種下拉式。

您的價值進來<li>標籤。用戶下面的代碼來選擇你的值 -

// Click on the "From" textbox 

driver.findElement(By.xpath("//div[@id='roundWay']//li/input[@placeholder='From']")).click(); 

// Select the required from city 

driver.findElement(By.xpath("//ul[@class='city-name origin-city-name']//li[text()='Bagdogra (IXB)']")).click(); 
相關問題