首页 > 其他分享 >jvppeteer 工具

jvppeteer 工具

时间:2024-04-28 15:44:05浏览次数:18  
标签:String try html static jvppeteer 工具 null page

  1. 依赖
<dependency>
  <groupId>io.github.fanyong920</groupId>
  <artifactId>jvppeteer</artifactId>
  <version>1.1.5</version>
</dependency>
  1. 工具

import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import com.ruiyun.jvppeteer.options.Viewport;
import com.ruiyun.jvppeteer.protocol.network.Cookie;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ChromeUtil {

    @Getter
    private static Browser browser;

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";

    private static final String EXE_PATH = "C:\\Users\\xiaog\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";

    @Getter
    private static String cookie;

    public static void openBrowser() {
        try {
            String exePath = isWindows() ? EXE_PATH : "/usr/bin/google-chrome";
            ArrayList<String> argList = new ArrayList<>();
            Viewport viewport = new Viewport();
            viewport.setWidth(1920);
            viewport.setHeight(1024);
            viewport.setHasTouch(true);

            argList.add("--no-sandbox");
            argList.add("--disable-setuid-sandbox");
            argList.add("--disable-infobars");
//            argList.add("--incognito"); // 无痕模式
            argList.add("--disable-gpu");
            argList.add("--disable-web-security");
            argList.add("--disable-dev-shm-usage");
            argList.add("--ignore-certificate-errors");
            argList.add("--allow-running-insecure-content");
            argList.add("--mute-audio");
            argList.add("--start-maximized");

            LaunchOptions options = new LaunchOptionsBuilder()
                    .withArgs(argList)
                    .withHeadless(true)
                    .withViewport(viewport)
                    .withIgnoreDefaultArgs(Arrays.asList("--enable-automation"))
                    .withIgnoreHTTPSErrors(true)
                    .withExecutablePath(exePath)
                    .build();
            browser = Puppeteer.launch(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isWindows() {
        String osName = System.getProperty("os.name").toLowerCase();
        return osName.contains("windows");
    }

    public static void closeBrowser() {
        if (browser != null) {
            try {
                browser.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        /*try {
            if (isWindows()) {
                // 执行脚本
                Process process = Runtime.getRuntime().exec("taskkill -F /fi \"imagename eq chrome.exe\"");
                // 可选:等待脚本执行完成
                int exitCode = process.waitFor();
                log.info("exit code:" + exitCode);
            }else {
                // 执行脚本
                Process process = Runtime.getRuntime().exec("pkill -f \"(chrome)\"");
                // 可选:等待脚本执行完成
                int exitCode = process.waitFor();
                log.info("exit code:" + exitCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    private static void preHandler(Page page) {
        page.setUserAgent(USER_AGENT);
        page.setCacheEnabled(true);
        page.evaluateOnNewDocument("() => {const newProto = navigator.__proto__;delete newProto.webdriver; navigator.__proto__ = newProto;}");
        page.evaluateOnNewDocument("() => {window.chrome = {};window.chrome.app = {InstallState: 'hehe',RunningState: 'haha',getDetails: 'xixi',getIsInstalled: 'ohno',};window.chrome.csi = function () {};window.chrome.loadTimes = function () {};window.chrome.runtime = function () {};}");
        page.evaluateOnNewDocument("() => {Object.defineProperty(navigator, 'userAgent', {get: () =>'"+USER_AGENT+"',});}");
        page.evaluateOnNewDocument("() => {Object.defineProperties(navigator,{ webdriver:{ get: () => undefined } }) }");
        page.evaluateOnNewDocument("() => {Object.defineProperty(navigator, 'plugins', {get: () => [{0: {type: 'application/x-google-chrome-pdf',suffixes: 'pdf',description: 'Portable Document Format',enabledPlugin: Plugin,},description: 'Portable Document Format',filename: 'internal-pdf-viewer',length: 1,name: 'Chrome PDF Plugin',},{0: {type: 'application/pdf',suffixes: 'pdf',description: '',enabledPlugin: Plugin,},description: '',filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai',length: 1,name: 'Chrome PDF Viewer',},{0: {type: 'application/x-nacl',suffixes: '',description: 'Native Client Executable',enabledPlugin: Plugin,},1: {type: 'application/x-pnacl'," +
                "suffixes: '',description: 'Portable Native Client Executable',enabledPlugin: Plugin,},description: '',filename: 'internal-nacl-plugin',length: 2,name: 'Native Client',},],});}");
        page.evaluateOnNewDocument("() => {const originalQuery = window.navigator.permissions.query; window.navigator.permissions.query = (parameters) =>parameters.name === 'notifications'  ?  Promise.resolve({ state: Notification.permission })   :  originalQuery(parameters);}");
        page.evaluateOnNewDocument("() => {const getParameter = WebGLRenderingContext.getParameter;WebGLRenderingContext.prototype.getParameter = function (parameter) {if (parameter === 37445) {return 'Intel Inc.';}if (parameter === 37446) {return 'Intel(R) Iris(TM) Graphics 6100';}return getParameter(parameter);};}");
        page.evaluateOnNewDocument("() =>{ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); }");
    }

    public static String getPage(String url) {
        String html = null;
        Page page = null;
        try {
            page = browser.newPage();
            preHandler(page);
            page.goTo(url);
            setCookie(page.cookies());
            html = page.content();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (page != null) {
                try {
                    page.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return html;
    }

    public static String getPage(String url,long delay) {
        String html = null;
        Page page = null;
        try {
            page = browser.newPage();
            preHandler(page);
            page.goTo(url);
            Thread.sleep(delay);
            page.evaluate("() => window.stop()");
            setCookie(page.cookies());
            html = page.content();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (page != null) {
                try {
                    page.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return html;
    }

    public static void setCookie(List<Cookie> cookieList) {
        cookie = cookieList.stream()
                .map(x -> x.getName()+"="+x.getValue())
                .collect(Collectors.joining("; "));
    }

    public static String getPage(String url,String waitElementSelector) {
        String html = null;
        Page page = null;
        try {
            page = browser.newPage();
            preHandler(page);
            page.goTo(url);
            page.waitForSelector(waitElementSelector);
            setCookie(page.cookies());
            html = page.content();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (page != null) {
                try {
                    page.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return html;
    }

    public static String getPageByScroll(String url,int delay,int scrollNum,long scrollDelay) {
        String html = null;
        Page page = null;
        try {
            page = browser.newPage();
            preHandler(page);
            page.goTo(url);
            Thread.sleep(delay);
            setCookie(page.cookies());
            long half = scrollDelay / 2;
            for (int i = 0; i < scrollNum; i++) {
                Thread.sleep(half);
                page.evaluate("() => { window.scrollTo(0,document.body.scrollHeight); }");
                Thread.sleep(half);
                page.evaluate("() => { window.scrollTo(0,0); }");
            }
            html = page.content();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (page != null) {
                try {
                    page.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return html;
    }

    public static String getPageByScroll(String url,int scrollNum,long scrollDelay,String waitElementSelector) {
        String html = null;
        Page page = null;
        try {
            page = browser.newPage();
            preHandler(page);
            page.goTo(url);
            page.waitForSelector(waitElementSelector);
            setCookie(page.cookies());
            long half = scrollDelay / 2;
            for (int i = 0; i < scrollNum; i++) {
                Thread.sleep(half);
                page.evaluate("() => { window.scrollTo(0,document.body.scrollHeight); }");
                Thread.sleep(half);
                page.evaluate("() => { window.scrollTo(0,0); }");
            }
            html = page.content();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (page != null) {
                try {
                    page.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return html;
    }

    public static Object executeJs(String jsCode) {
        try {
            Page page = browser.pages().get(0);
            return page.evaluate(jsCode);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

标签:String,try,html,static,jvppeteer,工具,null,page
From: https://www.cnblogs.com/xiaogblog/p/18163867

相关文章

  • windows系统,大文本文件打开工具
    在Windows系统中,打开大文本文件的工具有多种选择。以下是一些推荐的软件:LogView:这是一款能够快速打开大文件的工具,对于300MB以上的文件,它基本上能在一分钟内打开。虽然打开大文件时可能会占用较多的内存,但它的处理速度相对较快,使得它成为处理大文本文件的理想选择。EditPlus:Edi......
  • 厉害了!这个工具帮助你生成朋友圈转发截图
    大家好,我是Java陈序员。在日常的工作生活中,我们经常会遇到应付各类强制要求转发朋友圈的行为,或者是朋友圈集赞的行为。今天,给大家介绍一个工具,可以帮助你生成朋友圈转发截图。关注微信公众号:【Java陈序员】,获取开源项目分享、AI副业分享、超200本经典计算机电子书籍等。项......
  • 记一次5分钟大模型生成物流网关多域名配置工具
    工具解决的问题小哥工作台配置物流网关配置一个接口,需要三个服务域名(自营、3pl、港澳),三个环境(测试、UAT、正式),3*3相当于需要配置9次,其中除了别名,其他都配置基本相同。通过大模型生成一个工具录入一次接口,生成9个配置文件。 步骤一:定义接口配置标准格式   步骤二:生......
  • 效率工具RunFlow完全手册之局域网传输篇
    本篇将向您介绍如何使用RunFlow在局域网(又称内网)内传输文件,同步剪贴板,无论是家庭局域网还是办公室局域网,都能轻松搞定文件传输以及剪贴板同步,如果您还没有安装RunFlow,可点这里去下载。为什么不推荐使用微信、QQ、钉钉、飞书等传输文件,要使用局域网传输呢?1.私密,文件和剪贴板都是......
  • 开发工具IDEA
    IDEA个人使用偏好,笔记。图居多,文字少,可自行参考(个人使用版本:2021.2.2)由于某些原因限制,所以不解释为什么还不更新使用新版本,可自行检索,答案很少,但存在即合理。有疑问可私信!下载步骤:进官网官网,https://www.jetbrains.com.cn/切换语言  选择工具  ......
  • linux系统性能及调优工具
    转自:https://blog.csdn.net/bandaoyu/article/details/95407670本文随时更新,链接:https://blog.csdn.net/bandaoyu/article/details/95407670一、Top常用命令 top-d5(每隔五秒刷新一次进程列表) top-uroot(只显示以root用户启动的进程) top-p1(只......
  • MBR2GPT.exe 是一个用于将磁盘从MBR分区转换为GPT分区的工具,而不会修改或删除磁盘上的
    MBR2GPT.exe是一个用于将磁盘从MBR分区转换为GPT分区的工具,而不会修改或删除磁盘上的数据。这个工具允许在Windows环境中执行转换操作,而不仅限于Windows预安装环境。它提供了一些选项来验证磁盘是否可以安全地转换,并执行实际的转换操作。在使用这个工具之前,用户可以选择进行......
  • 【排课小工具】项目需求的搜集与整合
    计划写一系列随笔,记录一个工具软件的开发过程,这是第一篇随笔,写本篇随笔的初衷是帮助我整理一下当前的需求详情,同时复习最近所需的软件工程相关知识,如果能对读者有所帮助,那算是这篇文章产生的额外价值了。需要注意的是,这不是一篇遵循标准规格的需求文档,因为其中可能夹杂着知识注解......
  • EPAI手绘建模APP常用工具栏_1
    1、常用工具栏 图 1 常用工具栏(1) 撤销(2) 重做(3) 删除(4) 复制① 选中场景中的模型后,复制按钮变成可用状态,否则变成禁用状态。可以选择多个模型一起复制。(5) 变换图 2 变换操作杆 3变换-输入数值移动图 4 变换-计算器输入数值① 选中场景中的......
  • 【排课小工具】项目需求的搜集与整合
    计划写一系列随笔,记录一个工具软件的开发过程,这是第一篇随笔,写本篇随笔的初衷是帮助我整理一下当前的需求详情,同时复习最近所需的软件工程相关知识,如果能对读者有所帮助,那算是这篇文章产生的额外价值了。需要注意的是,这不是一篇遵循标准规格的需求文档,因为其中可能夹杂着知识注解......