needmoreeasy EN 한국어
Learn

84 — Web: extracting links from a page

★★★★★ (5/5)web & text
Prerequisites
55 — Network, 69 — Patterns
You will end up with
fetching an HTML page from a local server and listing every link on it as a full URL

Guide 55 fetched JSON; guide 69 matched text with regex. A web page is just text too — HTML with tags around the content. Extracting the links is one regex over the raw page, and joining them with the server's address makes the full URLs a browser would use.

Steps

  1. Create a small page with three links. Save page.html:

  2. Serve the folder, as in guide 55:

  3. Fetching the page is the same urlopen call that fetched JSON; a page is text, so .decode("utf-8") gives the HTML:

    run it →
  4. Each link lives between href=" and the next ". The regex r'href="([^"]+)"' finds every one — [^"]+ means "one or more characters that are not a quote", and findall returns just the captured parts, as in guide 69. Save links.nme:

    run it →

    The page only knows story.txt — a short name relative to itself. Prepending base + "/" turns it into a full URL a browser could open: a page on the same server links with short names, and the client completes them.

  5. Run it:

    The three hrefs became three complete addresses. This is the same extraction step a link checker or a web crawler performs before fetching the next page.

Try it yourself

Add a link to another page that itself has links, then make the program fetch each found link and count how many of them exist (a 404 Not Found answer means a broken link — the HTTP error appears as an exception, guide 68 shows how to catch it). Or extract the page's src="..." image sources with the same pattern.

What you learned

  • HTML is text: fetch it with urlopen, decode it, search it with regex.
  • r'href="([^"]+)"' finds link targets; [^"]+ stops at the closing quote.
  • Relative links are short names; the client prepends the server address.
  • Link extraction is one regex — the first step of a link checker.

This page on GitHub