简单 Web Scraper
你将构建什么
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
获取 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
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
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
添加输入验证与异常处理
在主函数中添加 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
编写单元测试
使用 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,三个测试用例全部通过。
自己动手试试
import urllib.request
import re
# TODO: define fetch_page, extract_links, and scrape
# Then test with: scrape('https://example.com')
import urllib.request
import re
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
def extract_links(html):
pattern = r'href=["\']([^"\']+)["\']'
links = re.findall(pattern, html)
return sorted(set(links))
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')你学到了什么
你获取 web 内容, parsed HTML 使用 regex, handled network 错误, and deduplicated results — 核心的 web scraping, using 仅 Python's 标准库.
相关资源
相关练习
- Regex 模块测验
练习 re 模块.
- Predict try/except
异常 handling.
相关速查表
- Python Cheatsheet
urllib and re 引用.
相关错误
- URL 错误
无效 URLs.
- Unicode Decode 错误
Encoding issues.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- URL 错误
无效 URLs.
- Unicode Decode 错误
Encoding issues.