In your for loop if your xpath selector is correct, each site
is a WebElement
representing a <a>
element
So, to visit a link just do site.click()
in your for loop
Edit : New answer
I admit my answer was not helpful for your problem. Here is another solution which I think fits to what you need, tell me if it's working for you.
I have changed you selector because I didn't managed to make it work but feel free to use your own. The one that I use fetches the results links of a Google research.
The pause(xxx)
method is simply calling a Thread.sleep(xxx)
. I did this for testing convenience but you should better use the implicit or explicit wait implementation in Selenium API.
So here is the code :
// Searching "some keywords" on Google
driver.get("https://www.google.fr");
driver.findElement(By.id("gbqfq")).sendKeys("some keywords");
driver.findElement(By.id("gbqfb")).click();
pause(2000);
// Storing the results's links
List<WebElement> sites = driver.findElements(By.cssSelector("#rso div li div h3 a"));
// Storing the window showing the google's results
String googleResults = driver.getWindowHandle();
// Visiting the links
for(WebElement site : sites){
// Perform a SHIFT+click to open in a new window
Actions builder = new Actions(driver);
builder.moveToElement(site).keyDown(Keys.SHIFT).click().build().perform();
// IMPORTANT : Release the SHIFT key,
// otherwise the next Google link won't open in a new window
builder.keyUp(Keys.SHIFT).build().perform();
pause(500);
//Switch to the new open window
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
pause(2000);
/*
* Selenium is now focused on the new window
* Do you tests here
*/
// Closing the window
driver.close();
// Focusing back on the google's results
driver.switchTo().window(googleResults);
}