SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
Headless Chrome
Poslední sobota 31. 3. 2018
Proč?
Web
+ PDF
Na co dalšího?
• Testování aplikace/webu



https://about.gitlab.com/2017/12/19/moving-to-headless-chrome/

• Scraping



https://carstenwindler.de/software-testing/phantomjs-is-
discontinued/

• Server-side (pre)rendering pro SPA

https://github.com/prerender/prerender

• Performance timeline tracing
Jak na to?
Linux
# deb
alias chrome="google-chrome"
Windows
# see http://crbug.com/737678
chrome.exe --headless --disable-gpu ...
macOS
alias chrome="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
Docker
$ docker run 
--rm 
--name chrome 
-p 9222:9222 
jakubkulhan/chrome 
--headless 
--no-sandbox 
--remote-debugging-address=0.0.0.0 
--remote-debugging-port=9222
Docker
$ docker run 
--rm 
--name chrome 
--cap-add SYS_ADMIN 
-p 9222:9222 
jakubkulhan/chrome 
--headless 
--remote-debugging-address=0.0.0.0 
--remote-debugging-port=9222
$ chrome --headless --remote-debugging-port=9222
DevTools listening on ws://127.0.0.1:9222/devtools/
browser/09416f68-1b1e-49c2-b817-86e5b8ba718e
$ chrome --headless --dump-dom https://posobota.cz/
[0331/111647.273960:WARNING:dns_config_service_posix.cc(158)] dns_config has unhandled options!
[0331/111647.275008:ERROR:gpu_process_transport_factory.cc(1019)] Lost UI shared context.
<!DOCTYPE html>
<html class=""><head>
<meta charset="utf-8">
<title>Poslední sobota</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" media="screen,projection,tv" href="assets/combined.css">
<script src="assets/combined.js"></script>
<style type="text/css">.fancybox-margin{margin-right:0px;}</style></head>
<body>
...
$ chrome --headless --repl https://posobota.cz/
[0331/113150.981203:WARNING:dns_config_service_posix.cc(158)] dns_config has unhandled options!
[0331/113150.983272:ERROR:gpu_process_transport_factory.cc(1019)] Lost UI shared context.
[0331/113152.367207:INFO:headless_shell.cc(399)] Type a Javascript expression to evaluate or
"quit" to exit.
>>> location.href
{"result":{"type":"string","value":"https://www.posobota.cz/"}}
>>> quit
$ chrome --headless --print-to-pdf https://www.posobota.cz/
[0331/110056.799976:ERROR:gpu_process_transport_factory.cc(1019)] Lost UI shared context.
[0331/110056.799976:WARNING:dns_config_service_posix.cc(158)] dns_config has unhandled options!
[0331/110100.450183:INFO:headless_shell.cc(565)] Written to file output.pdf.
$ open output.pdf
$ chrome --headless --print-to-pdf https://www.scuk.cz/faktury/xxx
[0331/110432.990656:ERROR:gpu_process_transport_factory.cc(1019)] Lost UI shared context.
[0331/110432.994518:WARNING:dns_config_service_posix.cc(158)] dns_config has unhandled options!
[0331/110434.655689:INFO:headless_shell.cc(565)] Written to file output.pdf.
$ open output.pdf
$ chrome --headless --screenshot --window-size=1200x630 
https://www.scuk.cz/og/obchod/antoninovo-pekarstvi
[0331/111345.000540:WARNING:dns_config_service_posix.cc(158)] dns_config has unhandled options!
[0331/111345.001073:ERROR:gpu_process_transport_factory.cc(1019)] Lost UI shared context.
[0331/111420.539961:INFO:headless_shell.cc(565)] Written to file screenshot.png.
~$ open screenshot.png
Chrome Devtools
Protocol
chromedevtools.github.io/devtools-protocol/
github.com/jakubkulhan/chrome-devtools-protocol
$ composer require jakubkulhan/chrome-devtools-protocol
Spuštění Chrome
use ChromeDevtoolsProtocolContext;
use ChromeDevtoolsProtocolInstanceLauncher;
$ctx = Context::withTimeout(Context::background(), 10);
$launcher = new Launcher();
$instance = $launcher->launch($ctx);
try {
// ... work with $instance ...
} finally {
$instance->close();
}
Připojení se k existujícímu
use ChromeDevtoolsProtocolInstanceInstance;
$instance = new Instance("localhost", 9222);
// ... work with $instance ...
Dump DOM
$ctx = Context::withTimeout(Context::background(), 10);
$tab = $instance->open($ctx);
try {
$client = $tab->devtools();
try {
// ... work with $client ...
} finally {
$client->close();
}
} finally {
$tab->close($ctx);
}
Dump DOM
use ChromeDevtoolsProtocolModelPageNavigateRequest;
use ChromeDevtoolsProtocolModelRuntimeEvaluateRequest;
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://posobota.cz/")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$response = $client->runtime()->evaluate($ctx, EvaluateRequest::builder()
->setExpression("document.documentElement.outerHTML")
->build()
);
echo $response->result->value;
Print to PDF
use ChromeDevtoolsProtocolModelPagePrintToPDFRequest;
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://posobota.cz/")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$response = $client->page()->printToPDF($ctx, PrintToPDFRequest::builder()
//->setPaperWidth(8.3 /* inches */)
//->setPaperHeight(11.7 /* inches */)
//->setMarginTop(0.4 /* inches */)
//->setMarginRight(0.4 /* inches */)
//->setMarginBottom(0.4 /* inches */)
//->setMarginLeft(0.4 /* inches */)
//->setDisplayHeaderFooter(false)
//->setLandscape(true)
->build()
);
Screenshot
use ChromeDevtoolsProtocolModelPageCaptureScreenshotRequest;
use ChromeDevtoolsProtocolModelPageSetDeviceMetricsOverrideRequest;
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://www.scuk.cz/og/obchod/antoninovo-pekarstvi")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$client->page()->setDeviceMetricsOverride($ctx, SetDeviceMetricsOverrideRequest::builder()
->setWidth(1200)
->setHeight(630)
->setDeviceScaleFactor(1.0)
->setMobile(false)
->build()
);
$response = $client->page()->captureScreenshot($ctx, CaptureScreenshotRequest::builder()
->setFormat("png")
->build()
);
file_put_contents(
"screenshot.png",
base64_decode($response->data)
);
Screenshot celé stránky
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://posobota.cz/")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$contentSize = $client->page()->getLayoutMetrics($ctx)->contentSize;
$client->page()->setDeviceMetricsOverride($ctx, SetDeviceMetricsOverrideRequest::builder()
->setWidth($contentSize->width)
->setHeight($contentSize->height)
->setDeviceScaleFactor(1.0)
->setMobile(false)
->build()
);
$response = $client->page()->captureScreenshot($ctx, CaptureScreenshotRequest::builder()
->setFormat("png")
->build()
);
file_put_contents(
"page.png",
base64_decode($response->data)
);
Self-signed certificate
use ChromeDevtoolsProtocolModelSecurityCertificateErrorActionEnum;
use ChromeDevtoolsProtocolModelSecurityCertificateErrorEvent;
use ChromeDevtoolsProtocolModelSecurityHandleCertificateErrorRequest;
use ChromeDevtoolsProtocolModelSecuritySetOverrideCertificateErrorsRequest;
$client->security()->enable($ctx);
$client->security()->setOverrideCertificateErrors($ctx,
SetOverrideCertificateErrorsRequest::builder()
->setOverride(true)
->build()
);
$allowAllCertificates = function (CertificateErrorEvent $ev) use ($ctx, $client) {
$client->security()->handleCertificateError($ctx, HandleCertificateErrorRequest::builder()
->setEventId($ev->eventId)
->setAction(CertificateErrorActionEnum::CONTINUE)
->build()
);
};
$client->security()->addCertificateErrorListener($allowAllCertificates);
Cookies
use ChromeDevtoolsProtocolModelNetworkSetCookiesRequest;
$values = [
"foo" => "bar",
"baz" => "qux",
];
$cookies = [];
foreach ($values as $name => $value) {
$cookies[] = $cookie = new CookieParam();
$cookie->name = $name;
$cookie->value = $value;
$cookie->url = "https://httpbin.org/";
$cookie->domain = ".httpbin.org";
$cookie->path = "/";
$cookie->expires = time() + 365 * 24 * 60 * 60;
}
$client->network()->setCookies($ctx, SetCookiesRequest::builder()
->setCookies($cookies)
->build()
);
Cookies
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://httpbin.org/")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$response = $client->runtime()->evaluate($ctx, EvaluateRequest::builder()
->setExpression('document.cookie')
->build()
);
var_dump($response->result->value); // string(16) "foo=bar; baz=qux"
Cookie sharing
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://httpbin.org/cookies/set?iAm=cookie")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
Cookie sharing
$tab->close($ctx);
$tab = $instance->open($ctx);
Cookie sharing
$client->page()->enable($ctx);
$client->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://httpbin.org/")
->build()
);
$client->page()->awaitLoadEventFired($ctx);
$response = $client->runtime()->evaluate($ctx, EvaluateRequest::builder()
->setExpression('document.cookie')
->build()
);
var_dump($response->result->value); // string(10) "iAm=cookie"
Ale co když mezi taby cookies
sdílet nechci?
🤔
Browser contexts
$sessionA = $instance->createSession($ctx);
try {
// ... work with $sessionA ...
} finally {
$sessionA->close();
}
Browser contexts
$sessionA->page()->enable($ctx);
$sessionA->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://httpbin.org/cookies/set?iAm=cookie")
->build()
);
$sessionA->page()->awaitLoadEventFired($ctx);
Browser contexts
$sessionB->page()->enable($ctx);
$sessionB->page()->navigate($ctx, NavigateRequest::builder()
->setUrl("https://httpbin.org/")
->build()
);
$sessionB->page()->awaitLoadEventFired($ctx);
$response = $sessionB->runtime()->evaluate($ctx, EvaluateRequest::builder()
->setExpression('document.cookie')
->build()
);
var_dump($response->result->value); // string(0) ""
Další
• github.com/ChromeDevTools/awesome-chrome-devtools

• github.com/GoogleChrome/puppeteer
Díky!
Otázky?
@jakubkulhan

jakub.kulhan@gmail.com

jakub@scuk.cz

Contenu connexe

Dernier

Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
pritamlangde
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Dernier (20)

Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 

En vedette

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

En vedette (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

Headless Chrome