惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
量子位
S
Secure Thoughts
G
GRAHAM CLULEY
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
S
Security Affairs
Help Net Security
Help Net Security
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
H
Heimdal Security Blog
W
WeLiveSecurity
C
Check Point Blog

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
Saving and scraping a website with Puppeteer
2018-02-20 · via oida.dev | TypeScript, Rust

For some of my performance audits I need an exact copy of the webpage as it is served by my clients infrastructure. In some cases, it can be hard to get to the actual artefact. So it’s easier to fetch it from the web.

I found it particularly hard to save a website like it’s delivered with some of the tools around. curl and wget have troubles when dealing with an SPA. Parsed JavaScript fetches new resources. And you need a browser context to record every request and response.

That’s why I decided to use a headless Chrome instance with puppeteer to store an exact copy. Let’s see how this works!

Environment #

I’m using Node v9 and only need a couple of extra packages. puppeteer, in version 1.1.0. I’m also using fs-extra in version 5.0. It features a couple of nice shortcuts if you want to create folders and files in a single line.

const puppeteer = require('puppeteer'); // v 1.1.0
const { URL } = require('url');
const fse = require('fs-extra'); // v 5.0.0
const path = require('path');

And that’s it! The url and path packages are from core. I need both to extract filenames and create a proper path to store the files on my disk.

Scraping the website #

Here’s the full code for scraping and saving a website. Let it sink in for a bit, I’ll explain each point afterwards in detail.

async function start(urlToFetch) {
/* 1 */
const browser = await puppeteer.launch();
const page = await browser.newPage();

/* 2 */
page.on('response', async (response) => {
const url = new URL(response.url());
let filePath = path.resolve(`./output${url.pathname}`);
if (path.extname(url.pathname).trim() === '') {
filePath = `${filePath}/index.html`;
}
await fse.outputFile(filePath, await response.buffer());
});

/* 3 */
await page.goto(urlToFetch, {
waitUntil: 'networkidle2'
});

/* 4 */
setTimeout(async () => {
await browser.close();
}, 60000 * 4);
}

start('https://oida.dev');

Let’s dive into the code.

1. Creating a browser context #

First thing we have to do: Starting the browser!

const browser = await puppeteer.launch();
const page = await browser.newPage();

puppeteer.launch() creates a new browser context. It’s like starting up your browser from the dock or toolbar. It starts a headless Chromium instance, but you can point to a Chrome/Chromium browser on your machine as well.

Once the browser started, we open up a new tab with browser.newPage. And we are ready!

2. Record all responses #

Before we navigate to the URL we want to scrape, we need to tell puppeteer what to do with all the responses in our browser tab. Puppeteer has an event interface for that.

page.on('response', async (response) => {
const url = new URL(response.url());
let filePath = path.resolve(`./output${url.pathname}`);
if (path.extname(url.pathname).trim() === '') {
filePath = `${filePath}/index.html`;
}
await fse.outputFile(filePath, await response.buffer());
});

With every response in our page context, we execute a callback. This callback accesses a couple of properties to store an exact copy of the file on our hard disk.

  • The URL class from the url package helps us accessing parts of the response’s URL. We take the pathname property to get the URL without the host name, and create a path on our local disk with the path.resolve method.
  • If the URL has no extension name specified, we transform the file into a directory and add an index.html file. This is how static site generators create pretty URLs for servers where you can’t access routing directly. Works for us as well.
  • The response.buffer() contains all the content from the response, in the right format. We store it as text, as image, as font, whatever is needed.

It’s important that this response handler is defined before navigating to a URL. But navigating is our next step.

3. Navigate to the URL #

The page.goto method is the right tool to start navigation.

await page.goto(urlToFetch, {
waitUntil: 'networkidle2'
});

Pretty straightforward, but notice that I passed a configuration object where I ask for which event to wait. I set it to networkidle2, which means that there haven’t been more than 2 open network connections in the last 500ms. Other options are networkidle0, or the events load and domcontentloaded. The last events mirror the navigation events in the browser. Since some SPAs start executing after load, I rather want to listen to network connections.

After this event, the async function call resolves and we go back to our synchronous flow.

4. Wait a bit #

setTimeout(async () => {
await browser.close();
}, 60000 * 4);

To end execution and clean things up, we need to close the browser window with browser.close(). In that particular case I wait for 4 minutes. The reason is that this particular SPA that I crawled has some delayed fetching I wasn’t able to record with networkidle events. The response handler is still active. So all responses are recorded.

Bottom line #

And that’s all I needed for getting a copy of my client’s web application. Having a real browser context was a great help. puppeteer however is much more powerful. Look at their API and Readme to see some examples and get some ideas!

Related Articles