Skip to content

Commit ca304ee

Browse files
committed
fix: update downloading to be about JS
1 parent 64d2544 commit ca304ee

File tree

2 files changed

+116
-68
lines changed

2 files changed

+116
-68
lines changed

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

Lines changed: 102 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -11,61 +11,83 @@ import Exercises from './_exercises.mdx';
1111

1212
---
1313

14-
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.
14+
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.
1515

16-
## Starting a Python project
16+
## Starting a Node.js project
1717

18-
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:
18+
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:
1919

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

32-
Now let's test that all works. Inside the project directory we'll create a new file called `main.py` with the following code:
54+
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:
3355

34-
```py
35-
import httpx
56+
```js
57+
import process from 'node:process';
3658

37-
print("OK")
59+
console.log(`All is OK, ${process.argv[2]}`);
3860
```
3961

40-
Running it as a Python program will verify that our setup is okay and we've installed HTTPX:
62+
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:
4163

4264
```text
43-
$ python main.py
44-
OK
65+
$ node index.js mate
66+
All is OK, mate
4567
```
4668

4769
:::info Troubleshooting
4870

49-
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.
71+
If you see `ReferenceError: require is not defined in ES module scope, you can use import instead`, double check that in your `package.json` the type property is set to `module`.
72+
73+
If you see other 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.
5074

5175
:::
5276

5377
## Downloading product listing
5478

55-
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:
56-
57-
```py
58-
import httpx
79+
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:
5980

60-
url = "https://warehouse-theme-metal.myshopify.com/collections/sales"
61-
response = httpx.get(url)
62-
print(response.text)
81+
```js
82+
const url = "https://warehouse-theme-metal.myshopify.com/collections/sales";
83+
const response = await fetch(url);
84+
console.log(await response.text());
6385
```
6486

6587
If we run the program now, it should print the downloaded HTML:
6688

6789
```text
68-
$ python main.py
90+
$ node index.js
6991
<!doctype html>
7092
<html class="no-js" lang="en">
7193
<head>
@@ -79,15 +101,15 @@ $ python main.py
79101
</html>
80102
```
81103

82-
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.
104+
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.
83105

84106
:::tip Client and server, request and response
85107

86108
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:
87109

88110
- HTTP is an exchange between two participants.
89111
- The _client_ sends a _request_ to the _server_, which replies with a _response_.
90-
- 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.
112+
- 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.
91113

92114
:::
93115

@@ -109,28 +131,30 @@ First, let's ask for trouble. We'll change the URL in our code to a page that do
109131
https://warehouse-theme-metal.myshopify.com/does/not/exist
110132
```
111133

112-
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:
134+
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:
113135

114-
```py
115-
import httpx
136+
```js
137+
const url = "https://warehouse-theme-metal.myshopify.com/does/not/exist";
138+
const response = await fetch(url);
116139

117-
url = "https://warehouse-theme-metal.myshopify.com/does/not/exist"
118-
response = httpx.get(url)
119-
response.raise_for_status()
120-
print(response.text)
140+
if (response.ok) {
141+
console.log(await response.text());
142+
} else {
143+
throw new Error(`HTTP ${response.status}`);
144+
}
121145
```
122146

123147
If you run the code above, the program should crash:
124148

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

136160
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.
@@ -150,13 +174,15 @@ https://www.aliexpress.com/w/wholesale-darth-vader.html
150174
<details>
151175
<summary>Solution</summary>
152176

153-
```py
154-
import httpx
177+
```js
178+
const url = "https://www.aliexpress.com/w/wholesale-darth-vader.html";
179+
const response = await fetch(url);
155180

156-
url = "https://www.aliexpress.com/w/wholesale-darth-vader.html"
157-
response = httpx.get(url)
158-
response.raise_for_status()
159-
print(response.text)
181+
if (response.ok) {
182+
console.log(await response.text());
183+
} else {
184+
throw new Error(`HTTP ${response.status}`);
185+
}
160186
```
161187

162188
</details>
@@ -175,26 +201,30 @@ https://warehouse-theme-metal.myshopify.com/collections/sales
175201
Right in your Terminal or Command Prompt, you can create files by _redirecting output_ of command line programs:
176202

177203
```text
178-
python main.py > products.html
204+
node index.js > products.html
179205
```
180206

181-
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):
207+
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):
182208

183-
```py
184-
import httpx
185-
from pathlib import Path
209+
```js
210+
import { writeFile } from 'node:fs/promises';
186211

187-
url = "https://warehouse-theme-metal.myshopify.com/collections/sales"
188-
response = httpx.get(url)
189-
response.raise_for_status()
190-
Path("products.html").write_text(response.text)
212+
const url = "https://warehouse-theme-metal.myshopify.com/collections/sales";
213+
const response = await fetch(url);
214+
215+
if (response.ok) {
216+
const html = await response.text();
217+
await writeFile('products.html', html);
218+
} else {
219+
throw new Error(`HTTP ${response.status}`);
220+
}
191221
```
192222

193223
</details>
194224

195225
### Download an image as a file
196226

197-
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:
227+
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) for guidance. Especially check `Response.arrayBuffer()`. You can use this URL pointing to an image of a TV:
198228

199229
```text
200230
https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72cc8ff-fcd6-4141-b9cc-e1320f867785.jpg
@@ -203,16 +233,20 @@ https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72
203233
<details>
204234
<summary>Solution</summary>
205235

206-
Python offers several ways how to create files. The solution below uses [pathlib](https://docs.python.org/3/library/pathlib.html):
236+
Node.js offers several ways how to create files. The solution below uses [Promises API](https://nodejs.org/api/fs.html#promises-api):
237+
238+
```js
239+
import { writeFile } from 'node:fs/promises';
207240

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

212-
url = "https://warehouse-theme-metal.myshopify.com/cdn/shop/products/sonyxbr55front_f72cc8ff-fcd6-4141-b9cc-e1320f867785.jpg"
213-
response = httpx.get(url)
214-
response.raise_for_status()
215-
Path("tv.jpg").write_bytes(response.content)
244+
if (response.ok) {
245+
const buffer = Buffer.from(await response.arrayBuffer());
246+
await writeFile('tv.jpg', buffer);
247+
} else {
248+
throw new Error(`HTTP ${response.status}`);
249+
}
216250
```
217251

218252
</details>

sources/academy/webscraping/scraping_basics_javascript2/05_parsing_html.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,20 @@ $ pip install beautifulsoup4
3737
Successfully installed beautifulsoup4-4.0.0 soupsieve-0.0
3838
```
3939

40+
<!--
41+
:::tip Installing packages
42+
43+
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.
44+
45+
:::
46+
47+
:::info Troubleshooting
48+
49+
If you see other 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.
50+
51+
:::
52+
-->
53+
4054
Now let's use it for parsing the HTML. The `BeautifulSoup` object allows us to work with the HTML elements in a structured way. As a demonstration, we'll first get the `<h1>` element, which represents the main heading of the page.
4155

4256
![Element of the main heading](./images/h1.png)

0 commit comments

Comments
 (0)