![](/img/trans.png)
[英]How to get value from <h3> tag in Selenium WebDriver, Java
[英]How to get value from <h1> tag using class in Selenium WebDriver, Java
我有 html 代碼:
<div class="formCaptionContainer fill-width" data-dyn-bind="sizing: { width: $dyn.layout.Size.available }">
<h1 class="formCaption" data-dyn-bind="text: $data.Caption, click: $data.GoGridView">Expense report for Aditi Mehta - GS1-000282, testing2</h1>
<h2 class="formCaption-context" data-dyn-bind="text: $data.ParentTitleFields">Aditi Mehta : GS1-000282</h2>
</div>
我想從 /h1 標簽獲取 Aditi Mehta - GS1-000282, testing2 的價值費用報告
有誰知道怎么做?
我試過了 :
By.xpath(".//div[@class='formCaption']/h1";
上面顯示沒有找到元素
By.className("formCaption");
上圖顯示空白數據
By.xpath(".//*[@class='formCaption']/h1");
上面顯示沒有找到元素
您需要考慮您的 定位器策略,以下為一般案例方法提供了良好的偏好。
您還應該看看PageObject 模式。
該頁面似乎正在使用 JS 庫通過后期綁定/解析來顯示內容。 您的測試需要允許這樣做並等待您感興趣的頁面元素完全呈現。 從開發人員那里了解元素在解決之前和之后的樣子。 延遲解析是確定您的定位器策略時的一個考慮因素。 該策略應包括流暢的等待和元素出現的默認超時。
這不是固定單個定位器的問題。
你可以試試下面的Xpath。
String msg=driver.findElement(By.xpath("//div[@class='formCaptionContainer fill-width']/h1[@class='formCaption-context']")).getText();
這段代碼對我很有效
String textprint=driver.findElement(By.xpath("//h2[@class='formCaption-context']")).getText();
System.out.println(textprint);
希望它能解決你的問題
試試這個
String msg= driver.findElement(By.xpath(//div[contains(@class='formCaptionContainer')]/h1 ).getText();
根據您共享的HTML
,節點屬性在我看來是動態的。 所以我們必須按如下方式誘導WebDriverWait
:
new WebDriverWait(driver, 10).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//h1[@class='formCaption']"), "Aditi Mehta - GS1-"));
System.out.println(driver.findElement(By.xpath("//h1[@class='formCaption']")).getAttribute("innerHTML"));
感謝你的幫助。 它現在工作正常。 我使用下面的代碼
By headingExpenseText = By.xpath("//*[@class='formCaption'][contains(text(),'Expense report for')]");
public String getTitleEx()
{
return driver.findElement(headingExpenseText).getAttribute("innerHTML");
}
這對我有用:
String titleElem = driver.findElement(By.xpath("//*[@class='formCaptionContainer fill-width']/h1")).getAttribute("innerHTML");
assertEquals("Worked", titleElem);
您究竟需要什么,網頁上顯示的數據或 HTML 代碼中使用的 textValue?
如果您的定位器是正確的,那么您可以嘗試使用getAttibute("innerHTML")
代替getText()
,如下所示,
By.xpath("//*[@class='formCaption'][contains(text(),'Aditi Mehta')]").getAttribute("innerHTML");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.