我想找的是:
getElementByXpath(//html[1]/body[1]/div[1]).innerHTML
我需要得到元素的innerHTML使用JS(使用硒WebDriver/Java,因为WebDriver不能找到它本身),但如何?
我可以使用ID属性,但不是所有元素都有ID属性。
(固定)
我使用jsoup在Java中完成它。这符合我的需要。
我想找的是:
getElementByXpath(//html[1]/body[1]/div[1]).innerHTML
我需要得到元素的innerHTML使用JS(使用硒WebDriver/Java,因为WebDriver不能找到它本身),但如何?
我可以使用ID属性,但不是所有元素都有ID属性。
(固定)
我使用jsoup在Java中完成它。这符合我的需要。
当前回答
要使用xpath和javascript识别WebElement,必须使用evaluate()方法,该方法计算xpath表达式并返回结果。
document.evaluate ()
document.evaluate()返回一个基于XPath表达式和其他给定参数的XPathResult。
语法为:
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result
);
地点:
xpathExpression: The string representing the XPath to be evaluated. contextNode: Specifies the context node for the query. Common practice is to pass document as the context node. namespaceResolver: The function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used. resultType: An integer that corresponds to the type of result XPathResult to return using named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9. result: An existing XPathResult to use for the results. null is the most common and will create a new XPathResult
示范
例如,谷歌主页中的搜索框可以使用xpath作为//*[@name='q']来唯一识别,也可以使用Google -chrome-devtools控制台通过以下命令来识别:
$x("//*[@name='q']")
快照:
同样的元素也可以用document.evaluate()和xpath表达式来标识,如下所示:
document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
快照:
其他回答
要使用xpath和javascript识别WebElement,必须使用evaluate()方法,该方法计算xpath表达式并返回结果。
document.evaluate ()
document.evaluate()返回一个基于XPath表达式和其他给定参数的XPathResult。
语法为:
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result
);
地点:
xpathExpression: The string representing the XPath to be evaluated. contextNode: Specifies the context node for the query. Common practice is to pass document as the context node. namespaceResolver: The function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used. resultType: An integer that corresponds to the type of result XPathResult to return using named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9. result: An existing XPathResult to use for the results. null is the most common and will create a new XPathResult
示范
例如,谷歌主页中的搜索框可以使用xpath作为//*[@name='q']来唯一识别,也可以使用Google -chrome-devtools控制台通过以下命令来识别:
$x("//*[@name='q']")
快照:
同样的元素也可以用document.evaluate()和xpath表达式来标识,如下所示:
document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
快照:
对于像chrome命令行api中的$x(选择多个元素)尝试:
var xpath = function(xpathToExecute){
var result = [];
var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
result.push( nodesSnapshot.snapshotItem(i) );
}
return result;
}
MDN概述有帮助:https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
尽管许多浏览器都内置了$x(xPath)作为控制台,但以下是《JavaScript中使用xPath的入门》中一些有用但硬编码的代码片段的聚合,可以在脚本中使用:
快照
这给出了xpath结果集的一次性快照。DOM突变后,数据可能会过时。
Const $x = xp => { Const快照= document.evaluate( Xp,文档,null, XPathResult。ORDERED_NODE_SNAPSHOT_TYPE,零 ); 返回数组(snapshot.snapshotLength)[…] .map((_, i) => snapshot.snapshotItem(i)) ; }; console.log ($ x (' / / h2(包含(。、“foo”)])); < h2 > foo < / h2 > < h2 > foobar < / h2 > 酒吧< h2 > < / h2 >
一阶节点
const $xOne = xp => document.evaluate ( Xp,文档,null, XPathResult。FIRST_ORDERED_NODE_TYPE,零 ) .singleNodeValue ; console.log ($ xOne (' / / h2(包含(。、“foo”)])); < h2 > foo < / h2 > < h2 > foobar < / h2 > 酒吧< h2 > < / h2 >
迭代器
但是请注意,如果文档在迭代之间发生突变(文档树被修改),将使迭代失效,XPathResult的invalidIteratorState属性被设置为true,并且抛出NS_ERROR_DOM_INVALID_STATE_ERR异常。
函数*$xIter(xp) { 常量iter = document.evaluate( Xp,文档,null, XPathResult。ORDERED_NODE_ITERATOR_TYPE,零 ); For (;;) { const node = iter.iterateNext(); If (!node) { 打破; } 收益率节点; } } //转储到数组 console.log([…——xit美元(' / / h2(包含(。“foo”))))); //从生成器返回下一个项目 const xpGen = $xIter('//h2[text()="foo"]'); console.log (xpGen.next () value); < h2 > foo < / h2 > < h2 > foobar < / h2 > 酒吧< h2 > < / h2 >
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
System.setProperty("webdriver.chrome.driver", "path of your chrome exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath(".//*[@id='UserName']")).clear();
driver.findElement(By.xpath(".//*[@id='UserName']")).sendKeys(Email);
**Different way to Find Element:**
IEDriver.findElement(By.id("id"));
IEDriver.findElement(By.linkText("linkText"));
IEDriver.findElement(By.xpath("xpath"));
IEDriver.findElement(By.xpath(".//*[@id='id']"));
IEDriver.findElement(By.xpath("//button[contains(.,'button name')]"));
IEDriver.findElement(By.xpath("//a[contains(.,'text name')]"));
IEDriver.findElement(By.xpath("//label[contains(.,'label name')]"));
IEDriver.findElement(By.xpath("//*[contains(text(), 'your text')]");
Check Case Sensitive:
IEDriver.findElement(By.xpath("//*[contains(lower-case(text()),'your text')]");
For exact match:
IEDriver.findElement(By.xpath("//button[text()='your text']");
**Find NG-Element:**
Xpath == //td[contains(@ng-show,'childsegment.AddLocation')]
CssSelector == .sprite.icon-cancel