![](/img/trans.png)
[英]Unable to locate element using className in Selenium and Java
[英]Selenium - unable to locate element by classname
我想找到一個class = "big-number"
的p
標簽。 這是我寫的代碼:
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("big-number")));
System.out.println(driver.getTitle());
System.out.println(myDynamicElement);
這是我的輸出:
[[FirefoxDriver: firefox on MAC (fed46ad4-9ca9-9344-a57a-1d336db3927c)] -> class name: big-number]
我無法識別錯誤,它給了我一個輸出,但對我來說毫無意義。 關於如何至少可以識別錯誤的任何提示?
我當然確定該元素存在,這是HTML代碼:
<div id="users-online-container" style="">
<img class="big-number-icon" src="images/usersOnline.png">
<p class="big-number">228</p>
<p class="caption">Users Online</p>
</div>
<div id="users-online-loading"></div>
發生TimeOutException是因為驅動程序無法在特定時間內找到元素。 我認為選擇器中存在問題。 如果您確定該元素始終可見並且存在於頁面上,請嘗試下一個代碼:
//Select first paragraph in div
driver.FindElement(By.CssSelector("#users-online-container .big-number"));
//if you have several p with same classes you could access any of them using index. e.g.
driver.findElements(By.CssSelector(".big-number"))[index];
選擇器可以是#users-online-container .big-number
或.big-number
。 兩者都會起作用。
嘗試下面的代碼。
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("big-number")));
// It will print the text of the Element:
system.out.println(myDynamicElement.getText());
另外,您嘗試在XPATH的幫助下找到元素,並確保您的定位符可以唯一地標識元素。 還要檢查IsDisplayed()和IsEnabled()是否返回True。
在您的代碼中,您正在打印將打印哈希碼的WebElement。 為了獲取Element的文本,您必須使用getText()方法。
希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.