[英]Unable to extract the text using gettext in Selenium WebDriver and also unable to click it
我无法在 Selenium WebDriver 中找到以下代码的gettext
。
<a id="551" class="blueTextNormal1 spc" onclick="sPh(this,'079');return false;" title="079">Country</a>
我想获得国家的价值。 我尝试使用xpath
:
driver.findElement(By.xpath("//*[@id='551']").getText())
但它没有返回任何值。 当我尝试
driver.findElement(By.xpath("//*[@id='551']")).getAttribute("title"))
我得到的值为“079”。
我该如何进行?
这也取决于代码。 试试下面的代码:
请使用getAttribute("innerHTML")
而不是getText()
,它将返回您要查找的内容,包括任何不可见的 HTML。
<div class="no-docs-selected">
<p class="icon-alert">Please select a doc</p>
</div>
我正在寻找Please select a doc
,但我没有成功使用getText()
。 但下面的一个工作。
driver.findElement(By.xpath("//p[@class='icon-alert']")).getAttribute("innerHTML");
我遇到了同样的问题,然后我将 .getText() 更新为.getAttribute("textContent")并且它起作用了。
您能够获得属性标题而不是文本真的很令人惊讶。
试试
driver.findelement(By.xpath("//a[@id='551' and contains(text(),'Country')]")).isDisplayed();
要么
driver.findelement(By.xpath("//a[@id='551' and text()='Country']")).isDisplayed();
我也有一个getAttribute("innerHTML")
工作的情况,但不是getText()
。 结果发现该元素存在,但不可见或不显示。
当我在调用getText()
之前首先滚动到元素时,它起作用了。
if(!element.isDisplayed())
scrollIntoView(element);
element.getText();
scrollIntoView
函数是这样的:
public void scrollIntoView(WebElement element) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
因此我不需要使用 getAttribute("innerHTML")`。
除非在复制到 Stack Overflow 时出现拼写错误,否则在 getText 之前缺少括号。 将driver.findElement(By.xpath("//*[@id='551']").getText())
改为driver.findElement(By.xpath("//*[@id='551']")).getText()
我尝试了以下代码,它非常适合我。
WebDriver driver = new ChromeDriver();
driver.get("C:\\test.html");
System.out.println(driver.findElement(By.xpath("//*[@id='551']")).getText());
System.out.println(driver.findElement(By.xpath("//*@id='551']")).getAttribute("title"));
使用<WebElement>.getAttribute("value")
提取文本。
String text1 = driver.findElementByXPath("//input[@value='EFASTGTC']/../ancestor::tr[1]/scipt[1]").getAttribute("innerText");
System.out.println("Value=" + text1);
如果您希望在脚本标记之间写入文本,则此代码将起作用。
这对我有用:
System.out.println(driver.findElement(By.id("error")).getAttribute("textContent"));
代码:
driver.get("https://login.salesforce.com/");
driver.findElement(By.id("username")).sendKeys("Hello");
driver.findElement(By.id("password")).sendKeys("Hello");
driver.findElement(By.id("Login")).click();
System.out.println(driver.findElement(By.id("error")).getAttribute("textContent"));
driver.close();
这对我有用。 我使用getAttribute("innerText")
而不是getText()
。
System.out.println(driver.findElement(By.id("modalError")).getAttribute("innerText"));
在类似的情况下,这对我有用:
.getAttribute("innerHTML");
.getAttribute("innerText");
.getAttribute("outerText");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.