简体   繁体   中英

how to get the id from the Xpath as a text

I had taken the xPath as below but I am not able to get the value 145666 when I try to print.

WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(@class,'mat-content')]//div[@id='demandTrackingID']")));

Now iam getting the below Expception:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //span[contains(@class,'mat-content')]//div[@id='TrackID']

Note: This Html Element is a Non Visible Element I need to inspect the panel and get this element as there is no field for this Element

HTML:

        <div _ngcontent-wbh-c179="" id="TrackID" class="disp-none">14566 </div>

Please try this:

WebElement trackid= driver.findElement(By.xpath("//span[contains(@class,'mat-content')]//div[@id='TrackID']"));
System.out.println("getid:"+ trackid.getText());

You will possible need to add an explicit wait before that to make element fully loaded before retrieving it's content

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 is ID not id

so use this:

WebElement trackid= driver.findElement(By.id("TrackID"));
System.out.println("getid:"+ trackid.getText());

The element that contains the text you want has an ID, TrackID , not to be confused with the "ID" text on the page. You can use that to locate the element more easily than the XPath you are currently using. Once you have the element, you can use WebDriverWait to wait for the element to contain text. Code is below.

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until((ExpectedCondition<Boolean>) d -> d.findElement(By.id("TrackID")).getText().length() != 0);

Given the class class="disp-none" on the element, I'm guessing that the element might not be visible. If this is the case, you'll have to use JavaScript to get the invisible text. Selenium was designed to only interact with visible elements and will throw an exception if you try to interact with elements that are not visible.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM