Headless Chrome 개발 도구 라이브러리에 대한 소개 예시

零下一度
풀어 주다: 2017-07-18 17:46:55
원래의
2392명이 탐색했습니다.

헤드리스 크롬은 Google 크롬을 헤드리스 모드로 실행하는 것을 의미합니다. 핵심은 구글 없이 구글을 운영하는 것! Chromium 및 Blink 렌더링 엔진에서 제공하는 최신 웹 플랫폼의 모든 기능을 명령줄로 변환합니다.

무슨 용도로 사용되나요?

Headless Browser는 시각적 사용자 인터페이스가 필요하지 않은 자동화된 테스트 및 서버를 위한 훌륭한 도구입니다. 예를 들어, 웹 페이지에서 몇 가지 테스트를 실행하거나, 웹 페이지에서 PDF를 생성하거나, 브라우저가 URL을 제출하는 방법을 확인하려고 합니다.

경고: Mac 및 Linux의 Chrome 59는 헤드리스 모드에서 실행될 수 있습니다. Windows 지원은 곧 제공될 예정입니다.

명령줄에서 Headless Chrome 실행

Chrome 설치(래더 필요)

  • 다운로드 주소

  • 여러 버전 비교

  • Chromium은 Chrome이 아니지만 기본적으로 Chrome의 콘텐츠는 다음에서 파생됩니다. 크로미움, 이건 오픈소스 버전이고 매시간 업데이트

  • 카나리는 체험판인데, 카나리아는 가스 등의 유독가스에 매우 민감합니다. 농도가 조금만 높아지면 지저귀는 소리가 멈추거나 심지어 죽기도 합니다. 카나리아는 가스 독가스 탐지의 조잡한 방법을 기다리는 중, 이 장면은 "용의 비밀"에서 황보의 작전에서도 볼 수 있습니다. 하하, 너무 멀리 가네요. 일일 빌드 버전입니다.

  • Dev는 개발 버전, 주간 빌드 버전

  • Beta는 테스트 버전, 월간 빌드 버전

  • Stable은 안정 버전, 일반적으로 한 달에 한 번 정도 불규칙하게 업데이트됩니다.

  • 업데이트 빈도 Chromium > Chrome Canary > Chrome 베타 > Chrome Stable

  • Chrome Dev, Chrome Beta 및 Chrome Stable은 동시에 하나만 표시될 수 있습니다.

  • Chromium, Chrome Canary 및 나머지 공존할 수 있습니다

  • Windows 플랫폼 다운로드는 온라인 설치 프로그램만 가능합니다. 오프라인 버전을 다운로드하려면 다운로드 페이지의 URLstandalone=1

命令行快捷配置(Mac环境)

~/.bashrc 中加入

alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
로그인 후 복사

重新打开终端,我们就可以直接通过 chrome打开稳定版的Chrome,chrome-canary打开试验版的Chrome了。

命令行启动Chrome

  • 参考官方说明, Headless模式需要Chrome Version >= 59

  • 使用Chrome打开百度首页(带界面),能看到浏览器的打开

chrome

  • 使用无界面模式启动Chrome打开百度首页(无界面),但不到浏览器界面打开,但任务栏会有图标

chrome --headless

  • 使用无界面模式启动Chrome并将页面转为PDF,可以看到output.pdf的输出

chrome --headless --print-to-pdf

  • 使用无界面模式启动Chrome并截图,可以看到screenshot.png的输出

chrome --headless --screenshot --window-size=414,736

  • 使用无界面模式启动Chrome并打开交互环境

chrome --headless --repl

  • 使用无界面模式启动Chrome,并开启调试Server

chrome --headless --remote-debugging-port=9222

  • 参考 Chrome命令行参数列表

命令行操作Headless Chrome

  • 确保已经启动Headless Chrome,并启用了调试Server

chrome --headless --remote-debugging-port=9222

  • 安装chrome-remote-interface

npm install chrome-remote-interface -g

  • 查看命令说明,这里可以进行各种相关操作

"
$ chrome-remote-interface

Usage: chrome-remote-interface [options] [command]

Commands:

  inspect [options] [<target>] inspect a target (defaults to the first available target)
  list                   list all the available targets/tabs
  new [<url>]            create a new target/tab
  activate <id>          activate a target/tab by id
  close <id>             close a target/tab by id
  version                show the browser version
  protocol [options]     show the currently available protocol descriptor

Options:

  -h, --help         output usage information
  -t, --host <host>  HTTP frontend host
  -p, --port <port>  HTTP frontend port
  -s, --secure       HTTPS/WSS frontend
로그인 후 복사

"

  • 打开一个新页面

chrome-remote-interface new

  • 查看刚打开的页面

chrome-remote-interface inspect

  • 查看当前页面的URL

>>> Runtime.evaluate({expression:'location.href'})standalone=1 매개변수를 추가하세요.

명령줄 빠른 구성(Mac 환경)

~/.bashrc

const chromeLauncher = require(&#39;chrome-launcher&#39;);//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别//chromeLauncher.run({chromeLauncher.launch({// port: 9222,chromeFlags: [&#39;--headless&#39;]}).then((chrome) => {// 拿到一个调试客户端实例console.log(chrome)chrome.kill();});
로그인 후 복사
로그인 후 복사

를 추가하고 터미널을 다시 열 수 있습니다. 를 통해 직접 Chrome의 안정 버전을 열 수 있습니다. chrome, chrome -canaryChrome의 실험용 버전을 엽니다.

명령줄에서 Chrome 시작

🎜🎜공식 지침을 참조하세요. 헤드리스 모드에는 Chrome 버전 >= 59🎜🎜🎜🎜Chrome을 사용하여 Baidu 홈페이지(인터페이스 포함)를 열면 브라우저가 열리는 것을 볼 수 있습니다🎜🎜 🎜chrome 🎜🎜🎜🎜인터페이스 없는 모드를 사용하여 Chrome을 시작하고 Baidu 홈페이지(인터페이스 없이)를 열 수 있지만 브라우저 인터페이스에서는 열리지 않지만 taskbar🎜🎜🎜chrome --headless 🎜🎜🎜🎜Chrome을 헤드리스 모드로 시작하고 페이지를 PDF로 변환하면 output.pdf</code의 출력을 볼 수 있습니다. >🎜🎜</ul>🎜<code >chrome --headless --print-to-pdf 🎜🎜🎜🎜Chrome을 헤드리스 모드로 시작하고 스크린샷을 찍으면 스크린샷의 출력을 볼 수 있습니다. .png🎜🎜 🎜chrome --headless --screenshot --window-size=414,736 🎜🎜🎜🎜Chrome을 헤드리스 모드로 시작하고 대화형 환경을 엽니다🎜🎜 🎜chrome --headless --repl🎜🎜🎜🎜Chrome을 헤드리스 모드로 시작하고 서버 디버깅을 활성화합니다🎜🎜🎜chrome --headless --remote- 디버깅-포트=9222🎜 🎜🎜🎜Chrome 명령줄 매개변수 목록을 참조하세요🎜🎜🎜명령줄 작업 Headless Chrome🎜🎜🎜🎜Headless Chrome을 시작하고 디버깅 서버를 활성화했는지 확인하세요🎜 🎜🎜chrome --headless --remote-debugging-port=9222🎜🎜🎜🎜 chrome-remote-interface 설치🎜🎜🎜 npm install chrome-remote-interface -g< /code>🎜🎜🎜🎜명령 설명 보기, 여기에서 다양한 관련 작업을 수행할 수 있습니다🎜🎜</ul>🎜"🎜$ chrome-remote-interface🎜<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="sourceCode javascript">const chromeLauncher = require(&amp;#39;chrome-launcher&amp;#39;);const chromeRemoteInterface = require(&amp;#39;chrome-remote-interface&amp;#39;)//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别//chromeLauncher.run({chromeLauncher.launch({port: 9222,chromeFlags: [&amp;#39;--headless&amp;#39;]}).then((launcher) =&gt; {chromeRemoteInterface.Version({host:&amp;#39;localhost&amp;#39;,port:9222}).then(versionInfo =&gt; {console.log(versionInfo)});chromeRemoteInterface({host:&amp;#39;localhost&amp;#39;,port:9222}).then((chrome) =&gt; {//这里调用ChromeDevToolsProtocol定义的接口const {Network,Page} = chrome;Network.requestWillBeSent((params) =&gt; {let {request} = params;let {url} = request;console.log(url)});Promise.all([Network.enable(),Page.enable() ]).then(() =&gt; {Page.navigate({url:&amp;#39;https://www.baidu.com&amp;#39;})});setTimeout(() =&gt; {launcher.kill()},5000);})});</pre><div class="contentsignin">로그인 후 복사</div></div><div class="contentsignin">로그인 후 복사</div></div>🎜 "🎜🎜🎜🎜새 페이지 열기🎜🎜</ul >🎜<code>chrome-remote-interface new 🎜🎜🎜🎜방금 열린 페이지 보기🎜🎜🎜chrome- 원격 인터페이스 검사🎜🎜🎜🎜현재 페이지 URL 보기🎜🎜🎜>>> Runtime.evaluate({expression:'location.href'}) 🎜🎜🎜🎜🎜Headless Chrome을 프로그래밍 방식으로 실행🎜🎜 코드를 통해 명령줄을 호출하여 Chrome 디버깅 서버를 직접 시작합니다.🎜🎜위의 명령줄 실행 방법을 시스템 호출을 통해 직접 호출할 수 있습니다. 이 방법에는 크로스 플랫폼 상황에서 수행할 작업이 있습니다. 🎜

Google出品的Lighthouse 这个网页质量检查工具,有一个组件专门做这事,考虑了各种平台的兼容性问题,源码参考lighthouse-chromelauncher,这个组件现在已经单独独立出来,作为一个单独的NPM组件chrome-launcher,可以直接使用这个在Node平台下调用,其他平台的也可以此为参考。

const chromeLauncher = require(&#39;chrome-launcher&#39;);//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别//chromeLauncher.run({chromeLauncher.launch({// port: 9222,chromeFlags: [&#39;--headless&#39;]}).then((chrome) => {// 拿到一个调试客户端实例console.log(chrome)chrome.kill();});
로그인 후 복사
로그인 후 복사

通过客户端的封装组件进行浏览器交互

实现了ChromeDevTools协议的工具库有很多,chrome-remote-interface是NodeJS的实现。

Chrome调试Server开启的是WebSocket交互的相关实现,要用编程的方式实现还需要封装一些WebSocket命令发送、结果接收等这一系列操作,这些chrome-remote-interface已经帮我们做了,更多实例可以参考chrome-remote-interface的wiki。

const chromeLauncher = require(&#39;chrome-launcher&#39;);const chromeRemoteInterface = require(&#39;chrome-remote-interface&#39;)//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别//chromeLauncher.run({chromeLauncher.launch({port: 9222,chromeFlags: [&#39;--headless&#39;]}).then((launcher) => {chromeRemoteInterface.Version({host:&#39;localhost&#39;,port:9222}).then(versionInfo => {console.log(versionInfo)});chromeRemoteInterface({host:&#39;localhost&#39;,port:9222}).then((chrome) => {//这里调用ChromeDevToolsProtocol定义的接口const {Network,Page} = chrome;Network.requestWillBeSent((params) => {let {request}  = params;let {url} = request;console.log(url)});Promise.all([Network.enable(),Page.enable()
        ]).then(() => {Page.navigate({url:&#39;https://www.baidu.com&#39;})});setTimeout(() => {launcher.kill()},5000);})});
로그인 후 복사
로그인 후 복사

위 내용은 Headless Chrome 개발 도구 라이브러리에 대한 소개 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!