简体   繁体   English

在 Chrome 上使用 Java 将 SearchContext 转换为 Selenium 中的 WebElement

[英]Converting SearchContext to WebElement in Selenium with Java on Chrome

Service Now has changed to using shadow root like this Service Now 已经改为像这样使用 shadow root

<span id='s1'> <span id='s1'>
#shadow-root #影根
<button>Cancel</button> <button>取消</button>
<button>Submit</button> <button>提交</button>
</span> </span>

I can easily get the first span:我可以很容易地得到第一个跨度:

 WebElement sele = driver.findElement(By.xpath("//span[@id='s1']"));

And then get the shadow root:然后获取影子根:

 SearchContext sc = sele.getShadowRoot();

But it will not let you do a但它不会让你做一个

 sc.findElements(By.xpath(".//button'"));

or more preferably或更优选

 WebElement cancelButton = sc.findElement(By.xpath(".//button[.='Cancel']"));

You have to find with CS selector你必须用 CS 选择器找到

 sc.findElements(By.cssSelector(" button"));

and go through each button to get the text.和 go 通过每个按钮获取文本。 To make it worse, when I try更糟的是,当我尝试

 List<WebElement> buttons = sc.findElements(By.cssSelector(" button"));

because it says there is an error with "=" and it expects "<=".因为它说“=”有错误,它期望“<=”。 No idea why.不知道为什么。 Have to do a必须做一个

 for (WebElement wele : sc.findElements(By.cssSelector(" button")) {
   String txt = wele.getText();
   if (txt.equals("Cancel")) ... // whatever you want
 }

So my question is is there someway to convert "sc" to a WebElement?所以我的问题是有没有办法将“sc”转换为 WebElement? Even maybe someway to get itself?甚至可能以某种方式得到自己? The equivalent of相当于

 sc.findElement(By.xpath("."));

or someway to look for xpath with SearchContext?或者以某种方式使用 SearchContext 查找 xpath?

Looks like this discussion is exactly what you looking for.看起来这个讨论正是您要找的。
There are several answers given there to get the Shadow Root as a WebElement object.那里给出了几个答案以将 Shadow Root 作为WebElement object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM