• 通过java爬取动态网页


    爬取网页一般是用Python的PhantomJS比较多,当然java也可以爬网页,主要是靠Chrome-Headless(无头浏览器)模拟浏览器爬取网页的,该项目由google公司维护,相比于PhantomJS,拥有更好的性能及效率。

    使用java的话,需要加入webmagic和selenium的maven依赖包实现网页的获取。

      
    <dependency>
        <groupId>us.codecraftgroupId>
        <artifactId>webmagic-coreartifactId>
        <version>0.7.4version>
    dependency>
    <dependency>
        <groupId>us.codecraftgroupId>
        <artifactId>webmagic-extensionartifactId>
        <version>0.7.4version>
    dependency>
    
    <dependency>
        <groupId>org.seleniumhq.seleniumgroupId>
        <artifactId>selenium-javaartifactId>
        <version>3.13.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    WebMagic的有四大组件:

    1.PageProcessor

    PageProcessor接口负责解析页面,抽取有用信息,以及发现新的链接。WebMagic使用Jsoup作为HTML解析工具。
    因为我们需要执行自己的业务逻辑,所以需要实现此接口。

    import us.codecraft.webmagic.*;
    import us.codecraft.webmagic.processor.PageProcessor;
    import org.openqa.selenium.Cookie;
    import java.util.Set;
    
    public class MyPageProcessor implements PageProcessor {    
        private Set<Cookie> cookies = null;//用来存储cookie信息
        
         /**
         * 解析返回的数据page
         * @param page Downloader实现类下载的结果。
         */
        @Override
        public void process(Page page) {
        	//向Pipeline对象中设置输出结果,把解析的结果放到ResultItems中 	
            page.putField("html", page.getHtml().all());
        }
        
        //Site对象可以对爬虫进行一些配置配置,包括编码、抓取间隔、超时时间、重试次数等。
        private final Site site = new Site()
                .addHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")//添加header信息,当对方网站识别爬虫的时候,需要填写
                .setDomain("example.com")//输入你要爬的网页域名,不带http和https前缀
                .addCookie("token","auth")//通过F12看后台自己cookie的token值,填进去
                .setTimeOut(2000);//设置超时时间
    
        @Override
        public Site getSite() {
            if(cookies!=null && !cookies.isEmpty()){
                //将获取到的cookie信息添加到webmagic中
                for (Cookie cookie : cookies) {
                    site.addCookie(cookie.getName(),cookie.getValue());
                }
            }
            return site;
        }
        //执行业务逻辑
        public static void main(String[] args) {
            Spider.create(new MyPageProcessor())
                    // 初始访问url地址
                    .addUrl("https://www.baidu.com")
                    //.setDownloader(new MyDownloader())//可选择使用自定义的
                    //.addPipeline(new MyPipeline())  //自定义的Pipeline,不设置的话,信息自动打印到console界面上              
                    .run();// 执行爬虫
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    2.Downloader

    Downloader接口负责从互联网上下载页面,以便后续处理。
    一般若是抓取静态界面,仅仅使用上面的PageProcessor 的实现类就够了。但是,若是需要抓取动态页面的话,这样就不够了,尤其是现在很多网页都是vue或react建设的。
    在上面的例子中,我们请求某个页面,只会获得静态的页面,没有数据在里面。这是因为我们只是获得了某个url返回的html文档。
    一般,真实环境的访问获取到html文档后,还要执行多个api请求去后台获取数据,给用户显示出来。
    因此,我们的程序只能模拟浏览器去访问动态页面,等待浏览器执行完所有的数据请求之后,再将页面解析出来进行处理。

    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import us.codecraft.webmagic.downloader.Downloader;
    import us.codecraft.webmagic.*;
    import us.codecraft.webmagic.selector.PlainText;
    import org.openqa.selenium.Cookie;
    import java.util.Map;
    
    public class MyDownloader implements Downloader {
        //声明驱动
        private RemoteWebDriver driver;
        
        public MyDownloader() {
            //第一个参数是使用哪种浏览器驱动,第二个参数是浏览器驱动的地址
            System.setProperty("webdriver.chrome.driver","C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
            //创建浏览器参数对象
            ChromeOptions chromeOptions = new ChromeOptions();
            // 设置为 无界面浏览器 模式,若是不想看到浏览器打开,就可以配置此项
            // chromeOptions.addArguments("--headless");     
            chromeOptions.addArguments("--window-size=1440,1080");// 设置浏览器窗口打开大小
            this.driver = new ChromeDriver(chromeOptions); //创建驱动
        }
    
         /**
         * 由于selenium的默认域名为data;因此第一次必须跳转到登录页,才能加入对应域名
         * @param request Request 
         */
        @Override
        public Page download(Request request, Task task) {
            try {
                driver.get(request.getUrl());//第一次打开url,跳转到登录页            
                Thread.sleep(3000);//等待打开浏览器
                //获取从process返回的site携带的cookies,填充后第二次打开url
                Site site = task.getSite();
                if (site.getCookies() != null) {
                    for (Map.Entry<String, String> cookieEntry : site.getCookies()
                            .entrySet()) {
                        Cookie cookie = new Cookie(cookieEntry.getKey(),
                                cookieEntry.getValue());
                        driver.manage().addCookie(cookie);
                    }
                    //添加对应domain的cookie后,第二次打开url
                    driver.get(request.getUrl());
                }
                Thread.sleep(2000);
                driver.executeScript("window.scrollTo(0, document.body.scrollHeight - 1000)");//需要滚动到页面的底部,获取完整的数据
                Thread.sleep(2000);//等待滚动完成
                //获取页面,打包成Page对象,传给PageProcessor 实现类
                Page page = createPage(request.getUrl(), driver.getPageSource());            
                //driver.close();//看需要是否关闭浏览器
                return page;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        public void setThread(int threadNum) {
    
        }
    
        //构建page返回对象
        private Page createPage(String url, String content) {
            Page page = new Page();
            page.setRawText(content);
            page.setUrl(new PlainText(url));
            page.setRequest(new Request(url));
            page.setDownloadSuccess(true);
            return page;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    可能自己的电脑上没有chrome的驱动,下载地址如下:
    http://chromedriver.storage.googleapis.com/index.html
    解压到对应的路径就好了

    3.Pipeline

    Pileline是抽取结束后,进行数据处理的部分,它主要用于抽取结果的保存,也可以定制Pileline可以实现一些通用的功能。
    在这里我们可以指定输出的位置,可以是控制台也可以是文件,当然也可以用户自定义Pipeline实现数据导入到数据库中。

    import us.codecraft.webmagic.ResultItems;
    import us.codecraft.webmagic.Task;
    import us.codecraft.webmagic.pipeline.Pipeline;
    
    public class MyPipeline implements Pipeline {
        @Override
        public void process(ResultItems resultItems, Task task) {
            List<String> title1 = resultItems.get("title");
            List<String> content = resultItems.get("content");
            String substring = title1.get(0).substring(48, title1.get(0).indexOf(""));
            String fileName = StringUtils.trim(substring);
            html2doc(fileName, content.get(0));
        }
        //将html转换成word文档保存
        @SneakyThrows
        public void html2doc(String fileName, String content) {
            Document docAll = Jsoup.parse(content);//解析网页得到文档对象        
            com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4);// 设置纸张大小
            // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
            // ByteArrayOutputStream baos = new ByteArrayOutputStream();
            File file = new File("D:\\" + fileName + ".doc");
            RtfWriter2.getInstance(document, new FileOutputStream(file));
            document.open();//打开word文档
            Elements contexts = docAll.getElementsByTag("p");//获取正文内容
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            LinkedList<Object> list = new LinkedList<>();
            for (Element context : contexts) {
                if (context.html().contains("img")) {
                    Future<Image> future = executorService.submit(
                            () -> {
                                try {
                                    Image img = handleImage(context.select("img").get(0));
                                    return img;
                                } catch (IOException | DocumentException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }
                    );
                    list.add(future);
                } else {                
                    Paragraph paragraph = new Paragraph(context.text());//  文本正文                
                    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);// 正文格式左对齐
                    paragraph.setSpacingBefore(5);// 离上一段落(标题)空的行数                
                    paragraph.setFirstLineIndent(20);// 设置第一行空的列数
                    list.add(paragraph);
                }
            }
            executorService.shutdown();
            try {
                executorService.awaitTermination(1, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (Object o : list) {
                if (o instanceof Paragraph) {
                    document.add((Paragraph) o);
                }
                if (o instanceof Future) {
                    Image image = ((Future<Image>) o).get();
                    document.add(image);
                    //以下内容是将下载的图片保存到本地
                    //FileOutputStream fout = new FileOutputStream("D:\\img\\" + image.hashCode() + ".png");                
                    //fout.write(image.getRawData());//将字节写入文件
                    //fout.close();
                }
            }
            document.close();
        }
        //处理下载的图片
        public Image handleImage(Element image) throws IOException, DocumentException {
            // // 添加图片 Image.getInstance即可以放路径又可以放二进制字节流
            //图片路径
            String src = image.attr("data-origin");
            BufferedInputStream in = Jsoup.connect(src).ignoreContentType(true).maxBodySize(8000000).execute().bodyStream();//注意设置最大下载size,避免图片只能下载一半
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, length);
            }
            Image img = Image.getInstance(out.toByteArray());
            img.setAbsolutePosition(0, 0);
            img.setAlignment(Image.LEFT);// 设置图片显示位置
            img.scaleAbsolute(500, 300);// 直接设定显示尺寸
            in.close();
            out.close();
            return img;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
  • 相关阅读:
    HCIP-datacom
    音频抗丢包以及暴力重传实现抗丢包80%
    直方图均衡化(三,c#实现)
    C++学习路线(二十五)
    【C语言】求解数独 求数独的解的个数 多解数独算法
    【C++】vector的认识+模拟实现
    JSP Servlet JDBC MySQL CRUD 示例教程
    探秘Spring的设计精髓,深入解析架构原理
    元器件正反(极性)检测案例
    【计算机网络】 集线器、网桥、交换机、路由器看这一篇就懂了。实验: 路由器的作用,以及没有路由器的情况下,如何用三层交换机实现路由器的功能
  • 原文地址:https://blog.csdn.net/qq_40610003/article/details/126604534