问题
Is it possible to find an element and then wait on a child element of that element? I do not know the full xpath, because I'm looping through a collection of elements.
So lets say I find an element:
IWebDriver driver = new ChromeDriver(chromeDriverPath);
IWebElement firstElement = driver.FindElement(By.XPath("//table/tr[1]"));
Now there's a sub element I want to find, but pretend I can't know the full xpath because I'm looping through elements:
IWebElement secondElement = firstElement.FindElement(By.XPath("./td[5]"));
How can I wait for that secondElement to exist instead of just using FindElement. Normally I would wait on an element with the following code, but in this case I only know the xpath relative the xpath of the parent element.
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
var waitedForElement = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath("./td[5]")));
回答1:
Update:
The answer posted here should work for the above question
Original:
I was looking for the same answer. So far, I don't think there is a way. I've been looking a while for the answer to this question.
I'm guessing you would have to figure out the XPath of the element you wish to find a sub-element of. Once you do that, you add this to the font of the XPath you were going to use to find the subelement. Doesn't sound elegant. I'm going to try it tomorrow and see how it turns out.
Here is a some discussion in github concerning how to back out the XPath from an existing element. https://groups.google.com/forum/#!topic/selenium-users/kvGLSzl_GQE
protected String getXPath() {
String jscript = "function getPathTo(node) {" +
" var stack = [];" +
" while(node.parentNode !== null) {" +
" stack.unshift(node.tagName);" +
" node = node.parentNode;" +
" }" +
" return stack.join('/');" +
"}" +
"return getPathTo(arguments[0]);";
return (String) driver.executeScript(jscript, webElement);
}
Note of Caution:
from what I understand, you should not put a element.FindElemen() within the wait.Until(). The inner code gets executed first (FindElement) which defeats the purpose of the wait.Until() ... therefore, code structured as described in this warning won't wait.
PS: the above solution that i found did not work for me. It did give me an XPath, but it XPath was not for the element which I got the Xpath from.
来源:https://stackoverflow.com/questions/53233837/wait-for-a-sub-element-of-an-element-in-c-sharp-selenium