如何定位webelement?

时间:2018-02-13 10:10:47

标签: selenium selenium-webdriver

我无法在香料喷气机网站上选择出发城市来检查航班状态。

遵循的步骤:

login to http://www.spicejet.com
click on flight status link
select departure city as goa from drop down>>
=====

代码

package TestProject;    
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestFirefox {

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        //driver = new FirefoxDriver();
        System.setProperty("webdriver.chrome.driver",
                "C://Selenium Jars//Chrome//chromedriver_2.31//chromedriver.exe ");
         driver = new ChromeDriver();
        driver.get("http://www.spicejet.com/?utm_source=Brand%20Campaign%20_&utm_medium=cpc_google&utm_term=O%26D&utm_campaign=Spicejet%20all%20route%20campaign&gclid=CjwKCAiAtorUBRBnEiwAfcp_Y7LCureobkUcdJZY7dqfgx0nlxyYPQeMp6w4MKkaxBEF8QzpovceDBoCXKMQAvD_BwE");
    driver.findElement(By.xpath("//*[@id=\'buttons\']/div/div/ul/li[4]/a/span[2]")).click();
    Thread.sleep(3000);
    WebDriverWait wait =new WebDriverWait (driver, 15);

     WebElement test = wait.until(ExpectedConditions.elementToBeClickable(By.id("FlifoSearchInputCompactFlightStatus_originStation")));
        //WebElement test=driver.findElement(By.id("FlifoSearchInputCompactFlightStatus_originStation"));
    test.click();   
    //test.sendKeys("GOA(GOI)");
    Select s1=new Select(test);
    s1.selectByVisibleText("Agartala (IXA)");

    }

}

===== 错误

Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 45746
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.TimeoutException: Timed out after 15 seconds waiting for element to be clickable: By.id: FlifoSearchInputCompactFlightStatus_originStation
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'NPF0JVX9B', ip: '10.254.101.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir11036_19151}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.84, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: fcc55c734bff34b0f8d58fec53bd9c02
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:261)
    at TestProject.TestFirefox.main(TestFirefox.java:27)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"FlifoSearchInputCompactFlightStatus_originStation"}
  (Session info: chrome=63.0.3239.84)
  (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 286 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'NPF0JVX9B', ip: '10.254.101.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir11036_19151}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.84, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: fcc55c734bff34b0f8d58fec53bd9c02
*** Element info: {Using=id, value=FlifoSearchInputCompactFlightStatus_originStation}
    at sun.reflect.GeneratedConstructorAccessor9.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:413)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
    at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:899)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:897)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:205)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:1)
    at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:653)
    at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:1)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:238)
    ... 1 more

3 个答案:

答案 0 :(得分:1)

点击航班状态 - >在iframe中打开。所以你必须首先切换到iframe才能找到更多的元素。像这样修改你的代码,看我在等待之前添加了一行...

Reservation.varThatCanBeCheckedInSetTimer = true;
Reservation.set_Timer();

答案 1 :(得分:0)

以下代码对我有用:

driver.get("http://www.spicejet.com/");
driver.findElement(By.cssSelector("a[title='Flights']>span:nth-child(2)")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement dropdown = wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_ddl_originStation1_CTXT")));
dropdown.sendKeys("Goa (GOI)");

关于识别要素的一些注意事项:

  1. 开始使用HTML代码定位元素本身,而不是从父HTML开始。这将减少定位器中的大量噪音。有多种方法可以识别元素:id,name,linkText,css locator,xpath。
  2. 首选CSS定位器而不是Xpath。
  3. 避免使用绝对xpath,始终使用相对xpath。并尝试最小化相对性,即,如第一点所述,从元素HTML本身开始。

答案 2 :(得分:0)

要从下拉菜单中进行选择,您无需点击它。除去test.click();。并尝试以下,它应该工作。

WebElement element = driver.findElement(By.id("FlifoSearchInputCompactFlightStatus_originStation")));

Select departureCity = new Select(element);
departureCity.selectByVisibleText("Goa (GOI)");

或者您可以使用

departureCity.selectByValue("GOI");

如果抛出异常,请尝试在WebElement声明之前放置Thread.sleep(2000)或使用wait方法。