java爬虫爬取动态页面记录

最开始采用的HttpClient获取页面+Jsoup分析页面,但是获取不到想要的页面内容,发现自己想要的数据是js生成的,HttpClient加了头和Cookie还是获取不到,最后采用的htmlunit获取页面就可以了。

        WebClient webClient=new WebClient();
        WebClientOptions options = webClient.getOptions();
        options.setJavaScriptEnabled(true);
        options.setCssEnabled(false);
        options.setRedirectEnabled(true);
        try {
    
    
            HtmlPage htmlPage = webClient.getPage(url);
            // 等待JS驱动dom完成获得还原后的网页
            webClient.waitForBackgroundJavaScript(10000);
            String page=htmlPage.asXml();
            //分析页面
            analyse(page);
            webClient.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

使用WebMagic时,除了核心包外记得导入webmagic-selenium依赖就行。

        <dependency>
            <groupId>us.codecraft</groupId>
            <artifactId>webmagic-selenium</artifactId>
            <version>0.7.5</version>
        </dependency>

猜你喜欢

转载自blog.csdn.net/wflsyf/article/details/119480950