[英]Click on all the result links
Scenario: Go to Yahoo.com search for hotmail and click on all the search pages one at a time. 场景:转到Yahoo.com搜索hotmail,然后一次单击所有搜索页面。
My code: It just prints the link of the result pages. 我的代码:它只是打印结果页面的链接。 Is there a way to click pages 2,3,4 while there is no page left?
有没有办法单击页面2,3,4而没有页面呢?
public class QAJob {
@Test
public void jobSearch(){
WebDriver driver= new FirefoxDriver();
driver.get("https://yahoo.com");
driver.findElement(By.id("uh-search-box")).sendKeys("hotmail");
driver.findElement(By.id("uh-search-button")).click();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//scroll down
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,1000)", "");
List<WebElement> result_pages=driver.findElements(By.xpath("//div[contains(@class,'pagination')]//a[contains(@title,'')]"));
for (WebElement e: result_pages){
Actions action= new Actions(driver);
WebElement search_results=driver.findElement(By.xpath("//div[contains(@class,'pagination')]//a[contains(@title,'')]"));
System.out.println(e.getAttribute("outerHTML"));
}
}
}
In Selenium you can use the class name to find the element, in your case, the next
link has the class next
, so you need something like: 在Selenium中,您可以使用类名来查找元素,在您的情况下,
next
链接具有next
类,因此您需要类似以下内容:
driver.findElement(By.className("next").click();
To get to the next page. 进入下一页。
Fox example this script print all the links (up to page MAX_PAGES
): Fox示例,此脚本打印所有链接(至第
MAX_PAGES
页):
int MAX_PAGES = 3;
driver.get("https://yahoo.com");
driver.findElement(By.id("uh-search-box")).sendKeys("hotmail");
driver.findElement(By.id("uh-search-button")).click();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i < MAX_PAGES; i++) {
for (WebElement link : driver.findElements(By.cssSelector("h3.title > a"))) {
System.out.println("Title: " + link.getText() + " link" + link.getAttribute("href"));
}
driver.findElement(By.className("next")).click();
}
You can change the MAX_PAGES
variable to go further, or if you prefer to get all pages, you can catch the NotSuchElementException
that selenium will throw when we reach the last page. 您可以将
MAX_PAGES
变量更改为更远,或者,如果您希望获取所有页面,则可以捕获到硒到达最后一页时抛出的NotSuchElementException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.