Skip to content

Commit 07c3f0b

Browse files
authored
feat: update the downloading lesson of the JS2 course to be about JavaScript (#1657)
A part of #1584
1 parent 8d0b8bc commit 07c3f0b

File tree

1 file changed

+119
-67
lines changed

1 file changed

+119
-67
lines changed

sources/academy/webscraping/scraping_basics_javascript2/04_downloading_html.md

Lines changed: 119 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -12,61 +12,101 @@ import Exercises from './_exercises.mdx';
1212

1313
---
1414

15-
Using browser tools for developers is crucial for understanding the structure of a particular page, but it's a manual task. Let's start building our first automation, a Python program which downloads HTML code of the product listing.
15+
Using browser tools for developers is crucial for understanding the structure of a particular page, but it's a manual task. Let's start building our first automation, a JavaScript program which downloads HTML code of the product listing.
1616

17-
## Starting a Python project
17+
## Starting a Node.js project
1818

19-
Before we start coding, we need to set up a Python project. Let's create new directory with a virtual environment. Inside the directory and with the environment activated, we'll install the HTTPX library:
19+
Before we start coding, we need to set up a Node.js project. Let's create new directory and let's name it `product-scraper`. Inside the directory, we'll initialize new project:
2020

2121
```text
22-
$ pip install httpx
22+
$ npm init
23+
This utility will walk you through creating a package.json file.
2324
...
24-
Successfully installed ... httpx-0.0.0
25-
```
2625
27-
:::tip Installing packages
26+
Press ^C at any time to quit.
27+
package name: (product-scraper)
28+
version: (1.0.0)
29+
description: Product scraper
30+
entry point: (index.js)
31+
test command:
32+
git repository:
33+
keywords:
34+
author:
35+
license: (ISC)
36+
# highlight-next-line
37+
type: (commonjs) module
38+
About to write to /Users/.../product-scraper/package.json:
39+
40+
{
41+
"name": "product-scraper",
42+
"version": "1.0.0",
43+
"description": "Product scraper",
44+
"main": "index.js",
45+
"scripts": {
46+
"test": "echo \"Error: no test specified\" && exit 1"
47+
},
48+
"author": "",
49+
"license": "ISC",
50+
# highlight-next-line
51+
"type": "module"
52+
}
53+
```
2854

29-
Being comfortable around Python project setup and installing packages is a prerequisite of this course, but if you wouldn't say no to a recap, we recommend the [Installing Packages](https://packaging.python.org/en/latest/tutorials/installing-packages/) tutorial from the official Python Packaging User Guide.
55+
The above creates a `package.json` file with configuration of our project. While most of the values are arbitrary, it's important that the project's type is set to `module`. Now let's test that all works. Inside the project directory we'll create a new file called `index.js` with the following code:
3056

31-
:::
57+
```js
58+
import process from 'node:process';
3259

33-
Now let's test that all works. Inside the project directory we'll create a new file called `main.py` with the following code:
60+
console.log(`All is OK, ${process.argv[2]}`);
61+
```
3462

35-
```py
36-
import httpx
63+
Running it as a Node.js program will verify that our setup is okay and we've correctly set the type to `module`. The program takes a single word as an argument and will address us with it, so let's pass it "mate", for example:
3764

38-
print("OK")
65+
```text
66+
$ node index.js mate
67+
All is OK, mate
3968
```
4069

41-
Running it as a Python program will verify that our setup is okay and we've installed HTTPX:
70+
:::info Troubleshooting
71+
72+
If you see errors or are otherwise unable to run the code above, it likely means your environment isn't set up correctly. Unfortunately, diagnosing the issue is out of scope for this course.
73+
74+
Make sure that in your `package.json` the type property is set to `module`, otherwise you'll get the following warning:
4275

4376
```text
44-
$ python main.py
45-
OK
77+
[MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///Users/.../product-scraper/index.js is not specified and it doesn't parse as CommonJS.
78+
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
79+
To eliminate this warning, add "type": "module" to /Users/.../product-scraper/package.json.
4680
```
4781

48-
:::info Troubleshooting
82+
In older versions of Node.js, you may even encounter this error:
4983

50-
If you see errors or for any other reason cannot run the code above, it means that your environment isn't set up correctly. We're sorry, but figuring out the issue is out of scope of this course.
84+
```text
85+
SyntaxError: Cannot use import statement outside a module
86+
```
5187

5288
:::
5389

5490
## Downloading product listing
5591

56-
Now onto coding! Let's change our code so it downloads HTML of the product listing instead of printing `OK`. The [documentation of the HTTPX library](https://www.python-httpx.org/) provides us with examples how to use it. Inspired by those, our code will look like this:
57-
58-
```py
59-
import httpx
92+
Now onto coding! Let's change our code so it downloads HTML of the product listing instead of printing `All is OK`. The [documentation of the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) provides us with examples how to use it. Inspired by those, our code will look like this:
6093

61-
url = "https://warehouse-theme-metal.myshopify.com/collections/sales"
62-
response = httpx.get(url)
63-
print(response.text)
94+
```js
95+
const url = "https://warehouse-theme-metal.myshopify.com/collections/sales";
96+
const response = await fetch(url);
97+
console.log(await response.text());
6498
```
6599

100+
:::tip Asynchronous flow
101+
102+
First time you see `await`? It's a modern syntax for working with promises. See the [JavaScript Asynchronous Programming and Callbacks](https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks) and [Discover Promises in Node.js](https://nodejs.org/en/learn/asynchronous-work/discover-promises-in-nodejs) tutorials in the official Node.js documentation for more.
103+
104+
:::
105+
66106
If we run the program now, it should print the downloaded HTML:
67107

68108
```text
69-
$ python main.py
109+
$ node index.js
70110
<!doctype html>
71111
<html class="no-js" lang="en">
72112
<head>
@@ -80,15 +120,15 @@ $ python main.py
80120
</html>
81121
```
82122

83-
Running `httpx.get(url)`, we made a HTTP request and received a response. It's not particularly useful yet, but it's a good start of our scraper.
123+
Running `await fetch(url)`, we made a HTTP request and received a response. It's not particularly useful yet, but it's a good start of our scraper.
84124

85125
:::tip Client and server, request and response
86126

87127
HTTP is a network protocol powering the internet. Understanding it well is an important foundation for successful scraping, but for this course, it's enough to know just the basic flow and terminology:
88128

89129
- HTTP is an exchange between two participants.
90130
- The _client_ sends a _request_ to the _server_, which replies with a _response_.
91-
- In our case, `main.py` is the client, and the technology running at `warehouse-theme-metal.myshopify.com` replies to our request as the server.
131+
- In our case, `index.js` is the client, and the technology running at `warehouse-theme-metal.myshopify.com` replies to our request as the server.
92132

93133
:::
94134

@@ -110,28 +150,30 @@ First, let's ask for trouble. We'll change the URL in our code to a page that do
110150
https://warehouse-theme-metal.myshopify.com/does/not/exist
111151
```
112152

113-
We could check the value of `response.status_code` against a list of allowed numbers, but HTTPX already provides `response.raise_for_status()`, a method that analyzes the number and raises the `httpx.HTTPError` exception if our request wasn't successful:
153+
We could check the value of `response.status` against a list of allowed numbers, but the Fetch API already provides `response.ok`, a property which returns `false` if our request wasn't successful:
114154

115-
```py
116-
import httpx
155+
```js
156+
const url = "https://warehouse-theme-metal.myshopify.com/does/not/exist";
157+
const response = await fetch(url);
117158

118-
url = "https://warehouse-theme-metal.myshopify.com/does/not/exist"
119-
response = httpx.get(url)
120-
response.raise_for_status()
121-
print(response.text)
159+
if (response.ok) {
160+
console.log(await response.text());
161+
} else {
162+
throw new Error(`HTTP ${response.status}`);
163+
}
122164
```
123165

124166
If you run the code above, the program should crash:
125167

126168
```text
127-
$ python main.py
128-
Traceback (most recent call last):
129-
File "/Users/.../main.py", line 5, in <module>
130-
response.raise_for_status()
131-
File "/Users/.../.venv/lib/python3/site-packages/httpx/_models.py", line 761, in raise_for_status
132-
raise HTTPStatusError(message, request=request, response=self)
133-
httpx.HTTPStatusError: Client error '404 Not Found' for url 'https://warehouse-theme-metal.myshopify.com/does/not/exist'
134-
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404
169+
$ node index.js
170+
file:///Users/.../index.js:7
171+
throw new Error(`HTTP ${response.status}`);
172+
^
173+
174+
Error: HTTP 404
175+
at file:///Users/.../index.js:7:9
176+
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
135177
```
136178

137179
Letting our program visibly crash on error is enough for our purposes. Now, let's return to our primary goal. In the next lesson, we'll be looking for a way to extract information about products from the downloaded HTML.
@@ -151,13 +193,15 @@ https://www.aliexpress.com/w/wholesale-darth-vader.html
151193
<details>
152194
<summary>Solution</summary>
153195

154-
```py
155-
import httpx
196+
```js
197+
const url = "https://www.aliexpress.com/w/wholesale-darth-vader.html";
198+
const response = await fetch(url);
156199

157-
url = "https://www.aliexpress.com/w/wholesale-darth-vader.html"
158-
response = httpx.get(url)
159-
response.raise_for_status()
160-
print(response.text)
200+
if (response.ok) {
201+
console.log(await response.text());
202+
} else {
203+
throw new Error(`HTTP ${response.status}`);
204+
}
161205
```
162206

163207
</details>
@@ -176,26 +220,30 @@ https://warehouse-theme-metal.myshopify.com/collections/sales
176220
Right in your Terminal or Command Prompt, you can create files by _redirecting output_ of command line programs:
177221

178222
```text
179-
python main.py > products.html
223+
node index.js > products.html
180224
```
181225

182-
If you want to use Python instead, it offers several ways how to create files. The solution below uses [pathlib](https://docs.python.org/3/library/pathlib.html):
226+
If you want to use Node.js instead, it offers several ways how to create files. The solution below uses the [Promises API](https://nodejs.org/api/fs.html#promises-api):
183227

184-
```py
185-
import httpx
186-
from pathlib import Path
228+
```js
229+
import { writeFile } from 'node:fs/promises';
187230

188-
url = "https://warehouse-theme-metal.myshopify.com/collections/sales"
189-
response = httpx.get(url)
190-
response.raise_for_status()
191-
Path("products.html").write_text(response.text)
231+
const url = "https://warehouse-theme-metal.myshopify.com/collections/sales";
232+
const response = await fetch(url);
233+
234+
if (response.ok) {
235+
const html = await response.text();
236+
await writeFile('products.html', html);
237+
} else {
238+
throw new Error(`HTTP ${response.status}`);
239+
}
192240
```
193241

194242
</details>
195243

196244
### Download an image as a file
197245

198-
Download a product image, then save it on your disk as a file. While HTML is _textual_ content, images are _binary_. You may want to scan through the [HTTPX QuickStart](https://www.python-httpx.org/quickstart/) for guidance. You can use this URL pointing to an image of a TV:
246+
Download a product image, then save it on your disk as a file. While HTML is _textual_ content, images are _binary_. You may want to scan through the [Fetch API documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#reading_the_response_body) and the [Writing files with Node.js](https://nodejs.org/en/learn/manipulating-files/writing-files-with-nodejs) tutorial for guidance. Especially check `Response.arrayBuffer()`. You can use this URL pointing to an image of a TV:
199247

200248
```text
201249
https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72cc8ff-fcd6-4141-b9cc-e1320f867785.jpg
@@ -204,16 +252,20 @@ https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72
204252
<details>
205253
<summary>Solution</summary>
206254

207-
Python offers several ways how to create files. The solution below uses [pathlib](https://docs.python.org/3/library/pathlib.html):
255+
Node.js offers several ways how to create files. The solution below uses [Promises API](https://nodejs.org/api/fs.html#promises-api):
256+
257+
```js
258+
import { writeFile } from 'node:fs/promises';
208259

209-
```py
210-
from pathlib import Path
211-
import httpx
260+
const url = "https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72cc8ff-fcd6-4141-b9cc-e1320f867785.jpg";
261+
const response = await fetch(url);
212262

213-
url = "https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72cc8ff-fcd6-4141-b9cc-e1320f867785.jpg"
214-
response = httpx.get(url)
215-
response.raise_for_status()
216-
Path("tv.jpg").write_bytes(response.content)
263+
if (response.ok) {
264+
const buffer = Buffer.from(await response.arrayBuffer());
265+
await writeFile('tv.jpg', buffer);
266+
} else {
267+
throw new Error(`HTTP ${response.status}`);
268+
}
217269
```
218270

219271
</details>

0 commit comments

Comments
 (0)