应用程序使用硒爬行

时间:2014-09-02 18:18:00

标签: java selenium web-crawler

我试图访问网站中的所有链接,并想检查其状态(HTTP 200或500等)。我在处理点击某个链接后生成的新窗口时遇到问题。几个链接导致新的窗口,其他少数在同一个窗口打开。如何检查新窗口并切换到该窗口并返回主窗口。这是我的代码到目前为止:

public class TestLink {
    //list to save visited links
    static List<String> links = new ArrayList<String>();
    WebDriver driver;

    public TestLink(WebDriver driver) {
        this.driver = driver;
    }

    public void linkTest() {
        // loop over all the a elements in the page
            try{
            for(WebElement link : driver.findElements(By.tagName("a"))) {
                // Check if link is displayed and not previously visited
                if (link.isDisplayed() 
                            && !links.contains(link.getText())) {
                    // add link to list of links already visited
                    links.add(link.getText());
                    System.out.println(link.getText());
                    // click on the link. This opens a new page
                    link.click();
                    // call testLink on the new page
                    new TestLink(driver).linkTest();
                }
            }
            driver.navigate().back();
        }catch(StaleElementReferenceException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new HtmlUnitDriver();
        driver.get("http://www.flipkart.com/");
        // start recursive linkText
        new TestLink(driver).linkTest();
    }
}

修改

下面的代码适用于字符串网址,但我想要网站中每个链接的状态代码。如何动态构建每个链接的URL。

 public static int getResponseCode(String url) {
        try {
            WebClient client = new WebClient();
           // webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            client.getOptions().setThrowExceptionOnFailingStatusCode(false);
            if(url != null)
            return client.getPage(url).getWebResponse().getStatusCode();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        return 0;
    }

1 个答案:

答案 0 :(得分:0)

我认为这不是Selenium的预期用途,因此不鼓励使用此类用途。你最好使用一些http库甚至命令行实用程序,如cURL或wget与一些解析器一起使用。此外,webdriver不提供有关HTTP状态代码的任何信息。我会问这里 - 状态代码是什么?如果您加载新页面,通常会下载数十种不同的资源,每种资源都有自己的状态代码。

那就是说,如果你仍然想用Selenium做,那么是的,将所有可见的链接带到List<WebElement>并发送点击给他们。默认情况下,新链接在新窗口中打开,因此在单击之前必须知道您的父窗口句柄,在单击等待新窗口句柄然后切换到它之后,执行您需要执行的操作并关闭窗口,启动下一轮循环。查看文档here,您可能对getWindowHandles()switchTo()感兴趣。

对于状态代码,您需要通过代理路由您的流量。我会用browsermob。它可以获得HAR格式的性能数据,包括所有请求和响应,包括状态代码,因此您可以执行以下操作:

Har har = server.getHar();
if (har == null) return;
for (HarEntry entry : har.getLog().getEntries()){
    if ((String.valueOf(entry.getResponse().getStatus()).startsWith("4"))
            || (String.valueOf(entry.getResponse().getStatus()).startsWith("5"))){
          // take action
    }
}
相关问题