![](/img/trans.png)
[英]How to get text from a dynamic label id HTML field using its relative xpath in Katalon?
[英]how to get the id from the Xpath as a text
我采用了如下所示的xPath
,但是當我嘗試打印時無法獲得值145666
。
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(@class,'mat-content')]//div[@id='demandTrackingID']")));
現在我得到以下 Expception:
org.openqa.selenium.TimeoutException:預期條件失敗:等待 By.xpath 定位的元素的可見性://span[contains(@class,'mat-content')]//div[@id='TrackID']
注意:這個 Html 元素是一個不可見元素,我需要檢查面板並獲取這個元素,因為這個元素沒有字段
HTML:
<div _ngcontent-wbh-c179="" id="TrackID" class="disp-none">14566 </div>
請試試這個:
WebElement trackid= driver.findElement(By.xpath("//span[contains(@class,'mat-content')]//div[@id='TrackID']"));
System.out.println("getid:"+ trackid.getText());
您可能需要在此之前添加一個顯式等待,以便在檢索內容之前使元素完全加載
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(@class,'mat-content')]//div[@id='TrackID']")));
WebElement trackid= driver.findElement(By.xpath("//span[contains(@class,'mat-content')]//div[@id='TrackID']"));
System.out.println("getid:"+ trackid.getText());
id
是ID
不是id
所以用這個:
WebElement trackid= driver.findElement(By.id("TrackID"));
System.out.println("getid:"+ trackid.getText());
包含所需文本的元素有一個 ID TrackID
,不要與頁面上的“ID”文本混淆。 與您當前使用的 XPath 相比,您可以使用它更輕松地定位元素。 獲得元素后,您可以使用WebDriverWait
等待元素包含文本。 代碼如下。
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until((ExpectedCondition<Boolean>) d -> d.findElement(By.id("TrackID")).getText().length() != 0);
鑒於元素上的 class class="disp-none"
,我猜測該元素可能不可見。 如果是這種情況,您將不得不使用 JavaScript 來獲取不可見的文本。 Selenium 旨在僅與可見元素交互,如果您嘗試與不可見元素交互,則會拋出異常。
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until((ExpectedCondition<Boolean>) d -> d.findElement(By.id("TrackID")).getText().length() != 0);
WebElement element = driver.findElement(By.id("TrackID"));
String trackID = (JavascriptExecutor)driver.executeScript("return arguments[0].text", element);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.