[英]Selenium java can't get html text
我有這個 HTML 代碼:
<span id="slotTotal">
<span id="slotUsed">4</span>
/16
</span>
我想獲取文本 /16 但是當我嘗試時:
slotTot = driver.findElement(By.xpath("//*[@id='slotTotal']")).getText();
我收到此異常:org.openqa.selenium.InvalidSelectorException:嘗試定位元素時選擇器無效
我該如何解決? (如果我得到 4/16 也很好......)提前謝謝
獲取 SlotUsed 的文本
String slotUsed= driver.findElement(By.xpath("//span[@id='slotUsed']")).gettext();
System.out.println("Value of used slot"+slotUsed);
獲取小計(小計是第一個跨度元素的一部分)
String total=driver.findElement(By.xpath(".//span[@id='slotTotal']")).getText();
System.out.println("Total"+total);
String slotTot = driver.findElement(By.xpath("//span[normalize-space(@id='slotUsed']")).gettext();
希望這會幫助你。
使用xpath
使用following-sibling
:
//span[@id='slotUsed']/following-sibling::text()[1]
如下所示:
String slotTot = driver.findElement(By.xpath("//span[@id='slotUsed']/following-sibling::text()[1]")).getText();
有一個'.jar'和一個'javadoc'如果你能得到 HTML,那么從 HTML 頁面中檢索任何內容都很容易。 也許 Selenium 完全是矯枉過正。 它通常僅對您無法挑選的復雜 AJAX/JavaScript 有用。
import Torello.HTML.*;
import Torello.HTML.NodeSearch.*;
import Torello.Java.FileRW;
import java.util.*;
import java.io.IOException;
public class SO
{
public static void main(String[] argv) throws IOException
{
String html = FileRW.loadFileToString("so/y2019/Oct/q002/SO-Input.html");
// Convert the string to vectorized-html (a list)
Vector<HTMLNode> v = HTMLPage.getPageTokens(html, false);
// Get a copy of the OUTER <SPAN> ... </SPAN>
Vector<HTMLNode> slotTotalVec = InnerTagGetInclusive.first(v, "span", "id", TextComparitor.CN_CI, "slotTotal");
// Poll means to "REMOVE, and get a COPY OF" the INNER <SPAN> ... </SPAN>
Vector<HTMLNode> slotUsedVec = InnerTagPollInclusive.first(slotTotalVec, "span", "id", TextComparitor.CN_CI, "slotUsed");
// Util.textNodesString -> ignores all HTML Elements, and converts Text-Nodes to String
String slotUsedStr = Util.textNodesString(slotUsedVec).trim();
String slotTotalStr = Util.textNodesString(slotTotalVec).trim();
// Print it.
System.out.println("Slot Used: " + slotUsedStr + '\n' +
"Slot Total: " + slotTotalStr );
}
}
上述程序將產生以下 output 到 UNIX / BASH ZEA89B68C34CE4A63C0FZ77E7
@cloudshell:~$ java so.y2019.Oct.q002.SO
Slot Used: 4
Slot Total: /16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.