liveBook · Manning

Scraping

As explained in The Quick Python Book, Fourth Edition

Web scraping is the automated extraction of data from content delivered by websites or other web resources.

Web scraping automates data extraction from website content when the information is unavailable elsewhere. The process has two parts: fetch the page, then extract data from its HTML. section 22.4

A compact Beautiful Soup workflow can:

  • Read HTML and parse it with Beautiful Soup. section 22.4
  • Find links with the a selector, then read their text and href attributes. section 22.4
  • Select elements by class, then inspect their text and class attributes. section 22.4

Extracting a link and a special element

Given HTML containing <span class="special">this is special</span> and a link, select links with bs("a"), access the first result with [0], and read a_item.text or a_item["href"]. Select the special span with bs.select(".special"), then inspect its text or class. section 22.4

Listing 22.1 File test.html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>Title</title>
</head>

<body>
<h1>Heading 1</h1>

This is plan text, and is boring
<span class="special">this is special</span>

Here is a <a href="http://bitbucket.dev.null">link</a>

<hr>
<address>Ann Address, Somewhere, AState 00000
</address>
</body> </html>

Inspect the small HTML fixture used to demonstrate link and class-based extraction. section 22.4

Scraping requires practical restraint: scraping an uncontrolled site may be legally or ethically uncertain, and repeated requests can overload a smaller server. section 22.4 section 22.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates fetching, HTML parsing, selectors, indexing, text, and attributes, but defers complex scraping cases.
Examples
Uses a local HTML page containing a special span and link, plus a forecast page with repeated labeled rows.
What you can do after
Build it from scratch by parsing HTML with Beautiful Soup and extracting selected elements, text, and attributes.
How it connects
Connects scraping with web crawling, HTTP requests, HTML, APIs, JSON, XML, and Beautiful Soup.

Also explained in

Compare how 9 books explain scraping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.