简体   繁体   中英

Converting SearchContext to WebElement in Selenium with Java on Chrome

Service Now has changed to using shadow root like this

<span id='s1'>
#shadow-root
<button>Cancel</button>
<button>Submit</button>
</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

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

and go through each button to get the text. 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? Even maybe someway to get itself? The equivalent of

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

or someway to look for xpath with SearchContext?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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