我想找的是:

getElementByXpath(//html[1]/body[1]/div[1]).innerHTML

我需要得到元素的innerHTML使用JS(使用硒WebDriver/Java,因为WebDriver不能找到它本身),但如何?

我可以使用ID属性,但不是所有元素都有ID属性。

(固定)

我使用jsoup在Java中完成它。这符合我的需要。


你可以使用javascript的文档。求值在DOM上运行XPath表达式。我认为它在IE 6的浏览器中以某种方式得到了支持。

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate

IE支持selectNodes。

MSDN: https://msdn.microsoft.com/en-us/library/ms754523 (v = vs.85) . aspx

假设您的目标是开发和测试用于屏幕映射的xpath查询。然后使用Chrome的开发工具。这允许您运行xpath查询来显示匹配。或者在Firefox >9中,你可以用Web开发人员工具控制台做同样的事情。在早期版本中使用x- pathfinder或Firebug。

你可以使用document.evaluate:

方法的结果 如果可能,请指定类型。

它是w3标准化的,并且有完整的文档:https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate

函数getElementByXpath(path) { 返回文档。(path, document, null, XPathResult.).singleNodeValue FIRST_ORDERED_NODE_TYPE, null); } console.log(getElementByXpath("//html[1]/body[1]/div[1]")); < div > foo < / div >

https://gist.github.com/yckart/6351935

在mozilla开发者网络上也有一个很好的介绍:https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate


替代版本,使用XPathEvaluator:

函数getElementByXPath(xpath) 返回新的XPathEvaluator() .createExpression (xpath) XPathResult.FIRST_ORDERED_NODE_TYPE .evaluate(文档) .singleNodeValue } console.log(getElementByXPath("//html[1]/body[1]/div[1]")); < div > foo / bar < / div >

在Chrome开发工具中,您可以运行以下命令:

$x("some xpath")

对于像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

public class JSElementLocator {

    @Test
    public void locateElement() throws InterruptedException{
        WebDriver driver = WebDriverProducerFactory.getWebDriver("firefox");

        driver.get("https://www.google.co.in/");


        WebElement searchbox = null;

        Thread.sleep(1000);
        searchbox = (WebElement) (((JavascriptExecutor) driver).executeScript("return document.getElementById('lst-ib');", searchbox));
        searchbox.sendKeys("hello");
    }
}

确保您使用了正确的定位器。

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

为了直奔主题,您可以轻松地使用xapth。使用下面的代码来实现这一点的准确而简单的方法。请尝试提供反馈。谢谢。

JavascriptExecutor js = (JavascriptExecutor) driver;

    //To click an element 
    WebElement element=driver.findElement(By.xpath(Xpath));
    js.executeScript(("arguments[0].click();", element);

    //To gettext

    String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));

进一步阅读- https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f

要使用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;

快照:

尽管许多浏览器都内置了$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 >