Skip to content

简单 Web Scraper

中等 约 25 分钟

你将构建什么

Python script 那个获取 URL, extracts 所有 hyperlinks using regex, and prints 它们 — mini web scraper using 仅标准库.

学习目标

  • 获取 web 内容使用 urllib.请求
  • Extract 链接使用 regular 表达式
  • Handle network 错误使用 try/except
  • Clean and deduplicate extracted URLs

前置要求

  • 字符串 and 字符串方法
  • Regular 表达式 (re 模块)
  • 异常 handling

步骤

  1. 1

    获取 web page

    导入 urllib.请求 and 定义 fetch_page(URL) 那个返回 HTML 内容 as 字符串. Handle network 错误使用 try/except.

    代码
    import urllib.request
    
    def fetch_page(url):
        try:
            with urllib.request.urlopen(url) as response:
                html = response.read().decode('utf-8')
            return html
        except Exception as e:
            print(f"Error fetching {url}: {e}")
            return None

    预期结果

    fetch_page('https://example.com') 返回 HTML 内容 as 字符串.

  2. 2

    Extract 链接使用 regex

    导入 re and 定义 extract_links(HTML) 那个查找所有 href attributes in anchor 标签. 返回 deduplicated, 排序列表.

    代码
    import re
    
    def extract_links(html):
        pattern = r'href=["\']([^"\']+)["\']'
        links = re.findall(pattern, html)
        return sorted(set(links))

    预期结果

    extract_links(HTML) 返回排序列表的 唯一 URLs 找到 in href attributes.

  3. 3

    Put 它 together

    定义 scrape(URL) 那个获取 page, extracts 链接, and prints 每个 one 使用数字. 测试使用简单 URL.

    代码
    def scrape(url):
        html = fetch_page(url)
        if html is None:
            return
        links = extract_links(html)
        print(f"Found {len(links)} unique links:")
        for i, link in enumerate(links, 1):
            print(f"  {i}. {link}")
    
    # scrape('https://example.com')  # Uncomment to test

    预期结果

    numbered 列表的 唯一链接找到 on page.

  4. 4

    添加输入验证与异常处理

    在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。

    代码
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    预期结果

    非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。

  5. 5

    编写单元测试

    使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。

    代码
    import unittest
    
    class TestCoreFunc(unittest.TestCase):
        def test_normal(self):
            self.assertEqual(core_func(5), expected_5)
    
        def test_boundary(self):
            self.assertEqual(core_func(0), expected_0)
    
        def test_exception(self):
            with self.assertRaises(ValueError):
                core_func(-1)
    
    if __name__ == "__main__":
        unittest.main()

    预期结果

    运行 python test.py 后输出 OK,三个测试用例全部通过。

自己动手试试

你学到了什么

你获取 web 内容, parsed HTML 使用 regex, handled network 错误, and deduplicated results — 核心的 web scraping, using 仅 Python's 标准库.

相关资源

相关课程

  • Regex

    模式 matching for 链接.

  • 异常

    Network 错误 handling.

相关练习

相关速查表

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题