简体   繁体   中英

Is there a way to call nextElementSibling in Selenium Webdriver with Java?

I am working with a really messy page structure and the fragment that I am stuck on looks something like this:

<div>
    <h3>...</h3>
    <ul>...</ul>
    <h3>...</h3>
    <ul>...</ul>
    ...
</div>

I want to get one of the <ul> elements, so I could dig deeper into it and retrieve the actual value that I really need from there (it has a table inside it). Currently I am able to get the <h3> element that precedes the <ul> I am looking for. Since ul-elements don't have any unique identifiers that I could use to get them directly, I am hoping to achieve it by getting the element that comes after the h3-tag (on the same level). Is there a way to get what seems to be nextElementSibling? Thank you!

NB! h3 and ul elements don't have strict sequence number - there may or may not be a few elements before them, so getting an n-th child does not seem to be an option there.

You can achieve this with either xpath or by executing some javascript.

Xpath:

driver.find(By.xpath("//div/h3/following-sibling::ul[1]"));

JavaScript:

JavaScriptExecutor jsExec = (JavaScriptExecutor)driver;
WebElement ulElement = jsExec.executeScript("return arguments[0].nextSibling;", driver.find(By.cssSelector("div h3")));

Hope that helps!

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