无法获取getText()

时间:2018-08-07 12:06:28

标签: java eclipse selenium selenium-webdriver

嗨,我正在学习硒。我试图从FreeCrm.com的索引​​页中获取用户名的geText(),我的xpath从firebug是正确的。但得到NoSuchElementExceptopn

网址https://www.freecrm.com 我的代码

    @Test(description="verify the account holder name displaying correctly or not")
        public void AccHolderName() {
            driver=new FirefoxDriver();
            driver.get("https://www.freecrm.com/index.html");
            driver.findElement(By.name("username")).sendKeys("xxxxx");
            driver.findElement(By.name("password")).sendKeys("xxxx");
            driver.findElement(By.xpath("//input[@class='btn btn-small']")).click();
            String AccName=driver.findElement(By.xpath("//td[@class='headertable']//table//tbody//td[@class='headertext' and @align='left']")).getText().trim();
            System.out.println(AccName);

错误:无法找到元素:

{"method":"xpath","selector":"//td[@class='headertable']//table//tbody//td[@class='headertext' and @align='left']"}

请帮助我提供代码

1 个答案:

答案 0 :(得分:1)

由于元素在框架中,因此您必须首先切换到其内容:

new WebDriverWait(driver, 10).wait(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("mainpanel")));

无需等待,直到元素在页面上可见:

// wait at least 10 seconds until element will be visible on tha page
new WebDriverWait(driver, 10).wait(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//td[@class='headertable']//table//tbody//td[@class='headertext' and @align='left']"))));
String AccName = driver.findElement(By.xpath("//td[@class='headertable']//table//tbody//td[@class='headertext' and @align='left']")).getText().trim();
System.out.println(AccName);

//switch back to default content
driver.switchTo().defaultContent();

注意: ,您必须添加一些导入:

import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;