有没有办法在 Selenium WebDriver 中使用 JavaScript 通过 XPath 获取元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10596417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get element by XPath using JavaScript in Selenium WebDriver?
提问by pMan
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 use that in Selenium WebDriver/Java, since WebDriver can't find it itself), but how?
我需要使用 JS 获取元素的 innerHTML(在 Selenium WebDriver/Java 中使用它,因为 WebDriver 无法找到它本身),但是如何?
I could use ID attribute, but not all elements have ID attribute.
我可以使用 ID 属性,但并非所有元素都具有 ID 属性。
[FIXED]
[固定的]
I am using jsoup to get it done in Java. That works for my needs.
我正在使用 jsoup 在 Java 中完成它。这适合我的需要。
回答by yckart
You can use document.evaluate
:
您可以使用document.evaluate
:
Evaluates an XPath expression string and returns a result of the specified type if possible.
如果可能,计算 XPath 表达式字符串并返回指定类型的结果。
It is w3-standardizedand whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
它是w3 标准化并完整记录的: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
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
还有一个关于 mozilla 开发者网络的精彩介绍:https: //developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using XPathEvaluator
:
替代版本,使用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>
回答by Dmitry Semenyuk
In Chrome Dev Tools you can run the following:
在 Chrome Dev Tools 中,您可以运行以下命令:
$x("some xpath")
回答by Jay
For something like $x from chrome command line api (to select multiple elements) try:
对于 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;
}
This MDN overview helped: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
此 MDN 概述有帮助:https: //developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
回答by RobG
You can use javascript's document.evaluateto run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.
您可以使用 javascript 的document.evaluate在 DOM 上运行 XPath 表达式。我认为它在浏览器中以一种或另一种方式支持回到 IE 6。
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
MDN:https: //developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE supports selectNodesinstead.
IE 支持selectNodes。
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
MSDN:https: //msdn.microsoft.com/en-us/library/ms754523(v=vs.85) .aspx
回答by Martin Spamer
Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finderor Firebug.
假设您的目标是开发和测试屏幕地图的 xpath 查询。然后要么使用Chrome 的开发者工具。这允许您运行 xpath 查询以显示匹配项。或者在 Firefox >9 中,您可以使用Web Developer Tools 控制台执行相同的操作。在早期版本中使用x-path-finder或Firebug。
回答by Prerit Jain
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.
确保您使用的是正确的定位器。
回答by Alok Patel
**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
回答by Dharit Mehta
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);
回答by Sameera De Silva
To direct to the point , you can easily use xapth .The exact and simple way to do this using the below code . Kindly try and provide feedback .Thank you .
直接点,你可以很容易地使用 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']")));
Further readings - https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f