下面是 HTML 查询。
<div id="dvCount" style="">
<span>Total Log Count : </span>
<span id="spnLogCount">46</span>
</div>
我想在 Selenium WebDriver 中打印值 46
。请告诉我代码。
我正在使用以下代码,但无法获取该值:
WebElement Text= driver.Findelement(By.cssselector(xpath).gettext();
system.out.println("total" + Text);
但是这段代码不起作用。如何正确获取“spnLogCount”标记中的值?
最佳答案
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/rajnish/Desktop/my.html");
// way one
// you can create your custom x path
// one x path can be made directly using id of the span like
// xpath = //span[@id='spnLogCount']
// also not if you are not sure of the tag name then you can also use * in xpath like below
String myText = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
System.out.println("Total Log Count : " + myText);
// way two
// you can directly use id
myText = driver.findElement(By.id("spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
// way three
// if you are using css selector then for id you can use #
myText = driver.findElement(By.cssSelector("#spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
}
更新
driver.findElement(By.id("ui-id-3")).click();
driver.findElement(By.linkText("Info Log")).click();
driver.findElement(By.id("txtMessage")).sendKeys("Push Success");
driver.findElement(By.id("txtMachineName")).sendKeys("AC204");
driver.findElement(By.id("txtPortal")).sendKeys("91");
driver.findElement(By.id("btnSearch")).click();
// use it just before the sendkeys code like this
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dvCount']/span[2]")));
String text = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
System.out.println(text);
Hope this helps
关于java - 使用 selenium webdriver 打印所需的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36555887/