草庐IT

使用webmagic和selenium爬取动态网页

晓风残月淡 2024-01-11 原文

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

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

  <!--爬取网页-->
<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-core</artifactId>
    <version>0.7.4</version>
</dependency>
<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-extension</artifactId>
    <version>0.7.4</version>
</dependency>
<!--selenium依赖-->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.13.0</version>
</dependency>

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();// 执行爬虫
    }
}

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

可能自己的电脑上没有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;
    }
}

有关使用webmagic和selenium爬取动态网页的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  10. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

随机推荐