Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

后端 未结 10 1456
后悔当初
后悔当初 2020-11-22 10:53

I am looking for something like:

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

I need to get the innerHTML of elements using JS (to

相关标签:
10条回答
  • 2020-11-22 11:53

    You can use document.evaluate:

    Evaluates an XPath expression string and returns a result of the specified type if possible.

    It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate

    function getElementByXpath(path) {
      return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }
    
    console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
    <div>foo</div>

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

    There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate


    Alternative version, using XPathEvaluator:

    function getElementByXPath(xpath) {
      return new XPathEvaluator()
        .createExpression(xpath)
        .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)
        .singleNodeValue
    }
    
    console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
    <div>foo/bar</div>

    0 讨论(0)
  • 2020-11-22 11:53

    To identify a WebElement using xpath and javascript you have to use the evaluate() method which evaluates an xpath expression and returns a result.


    document.evaluate()

    document.evaluate() returns an XPathResult based on an XPath expression and other given parameters.

    The syntax is:

    var xpathResult = document.evaluate(
      xpathExpression,
      contextNode,
      namespaceResolver,
      resultType,
      result
    );
    

    Where:

    • 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

    Demonstration

    As an example the Search Box within the Google Home Page which can be identified uniquely using the xpath as //*[@name='q'] can also be identified using the google-chrome-devtools Console by the following command:

    $x("//*[@name='q']")
    

    Snapshot:

    googlesearchbox_xpath

    The same element can can also be identified using document.evaluate() and the xpath expression as follows:

    document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    

    Snapshot:

    document_evalute_xpath

    0 讨论(0)
  • 2020-11-22 11:53
    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");
        }
    }
    

    Make sure you are using the right locator for it.

    0 讨论(0)
  • 2020-11-22 11:53
    **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
    
    0 讨论(0)
提交回复
热议问题