Reputation: 2208
I am trying to get each of the below elements using
element = driver.findElement(By.className("code-list-item code-list-item-public "));
The output of inspect element is as follows.
<div class="column one-fourth codesearch-aside"></div>
<div class="column three-fourths codesearch-results">
<div class="sort-bar"></div>
<div id="code_search_results">
<div class="code-list">
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
<div class="code-list-item code-list-item-public "></div>
</div>
But it fails and throws the below error.
Caused by: org.openqa.selenium.InvalidSelectorException: The given selector code-list-item code-list-item-public is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Compound class names not permitted
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Also, How do I traverse through each of the classes? Each of these contain subparts which I would like to process further individually before moving to the next.
Upvotes: 2
Views: 14680
Reputation: 16201
I wouldn't worry about the class name that much if I don't have to. I would use css selector.
.code-list>div
Notice in css .
means class so I am pointing to the div with the class code-list
and >div
it allows us to select all child div
You also can use :nth-child()
function to grab a specific child div with index number
.code-list>div:nth-child(1)
The above css allows you to select the first child div
As per your screenshot
.code-list>div:nth-child(1)>a
A code block that may help OP to understand how this scenario should be handled
//maximizing the window for better view
driver.manage().window().maximize();
//a selector to find all the links on the page
By selector = By.xpath("//p[@class='title']/a[1]");
//finding the list of all elements
List<WebElement> list = driver.findElements(selector);
/*Iterating over the collection may throw StaleElementReference exception due to DOM refresh
according to my knowledge for loop is best in such case
*/
for (int i = 0; i<list.size(); i++){
new WebDriverWait(driver,10).until(ExpectedConditions.elementToBeClickable(selector));
//Click on the title
driver.findElements(selector).get(i).click();
//Navigating back to the main page. This is not feasible but no other option present due to page structure
driver.navigate().back();
}
Upvotes: 2