繁体   English   中英

点击所有结果链接

[英]Click on all the result links

场景:转到Yahoo.com搜索hotmail,然后一次单击所有搜索页面。

我的代码:它只是打印结果页面的链接。 有没有办法单击页面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"));    
        }
    }
}

在Selenium中,您可以使用类名来查找元素,在您的情况下, next链接具有next类,因此您需要类似以下内容:

driver.findElement(By.className("next").click();

进入下一页。

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();
    }

您可以将MAX_PAGES变量更改为更远,或者,如果您希望获取所有页面,则可以捕获到硒到达最后一页时抛出的NotSuchElementException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM