[英]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.