Selenium WebDriver에서 JavaScript를 사용하여 XPath로 요소를 얻는 방법이 있습니까?
나는 다음과 같은 것을 찾고있다 :
getElementByXpath(//html[1]/body[1]/div[1]).innerHTML
JS를 사용하여 요소의 innerHTML을 가져와야합니다 (WebDriver가 자체를 찾을 수 없으므로 Selenium WebDriver / Java에서 사용하려면).
ID 속성을 사용할 수 있지만 모든 요소에 ID 속성이있는 것은 아닙니다.
[결정된]
Java에서 완료하기 위해 jsoup을 사용하고 있습니다. 그것은 나의 필요를 위해 작동합니다.
당신은 사용할 수 있습니다 document.evaluate
:
XPath 표현식 문자열을 평가하고 가능한 경우 지정된 유형의 결과를 리턴합니다.
그것은 표준화 되고 전체적으로 문서화되어 있습니다 : 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
mozilla 개발자 네트워크에 대한 훌륭한 소개도 있습니다 : https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
다음을 사용하는 대체 버전 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>
Chrome 개발자 도구에서 다음을 실행할 수 있습니다.
$x("some xpath")
chrome command line 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
javascript의 document.evaluate 를 사용 하여 DOM에서 XPath 표현식을 실행할 수 있습니다 . IE 6으로 돌아가는 브라우저에서 어떤 방식 으로든 지원된다고 생각합니다.
MDN : https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE는 대신 selectNode 를 지원 합니다.
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
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-finder or Firebug.
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.
**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);
'Programing' 카테고리의 다른 글
줄 바꿈을 제거하지 않고 Ruby에서 여러 줄의 긴 문자열 나누기 (0) | 2020.05.01 |
---|---|
코드를 사용하여 버튼 클릭을 시뮬레이션하는 방법은 무엇입니까? (0) | 2020.05.01 |
nginx-nginx : [emerg] bind () ~ [::] : 80 실패 (98 : 이미 사용중인 주소) (0) | 2020.05.01 |
HTML 목록 스타일 형식 대시 (0) | 2020.05.01 |
오류 코드 : 2013. 쿼리 중 MySQL 서버 연결이 끊어졌습니다 (0) | 2020.05.01 |