网络爬虫

Ivan Lv6

这篇文章主要介绍构建一个网络爬虫中的各种细节.

首先网络爬虫本身可以视为一个图遍历算法, 例如 BFS 或是 DFS. 所以爬虫的代码实现本身会很类似于这些算法的框架.

在实现网络爬虫的过程中, 有这些细节需要注意:

  1. 对于 url 的去重, 在 href 中可能是相对路径, 需要使用 urllib.urljoin 函数来拼接
  2. 断点重续功能可以使用 sqlite 来追踪, 使用 status 字段 (pending, done, failed) 来保存任务状态, 每次执行时查询数据库中状态为 pending 的字段进行尝试
  3. 需要对 url 进行 normalization, 有一些 url 会带有 fragment, 例如 https://example.com/xxxx/#about 等. 这些都是同一个页面, 应当处理
  4. 对于一些反爬手段, 例如占位页反爬, 需要设置 headers (浏览器 Agent 属性来模拟用户发起的请求) 以及 Session 来保存服务器返回的 Cookie
  5. 可以对页面去重, 利用诸如 SimHash 等手段

断点重续伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 尝试插入初始链接
conn.execute("INSERT OR IGNORE INTO web_docs (url) VALUES (?)", (URL,))
# 获取非 pending 状态链接
try:
while row := conn.execute(
"SELECT url FROM web_docs WHERE status='pending' ORDER BY rowid LIMIT 1"
).fetchone():
page_url = row[0]

# 失败重试机制
try:
response = session.get(page_url, timeout=timeout)
response.raise_for_status()
html_content = response.content
soup = BeautifulSoup(html_content, "html.parser")
except requests.exceptions.HTTPError as e:
# request "https://example.com" failed: Error...
logger.warning(f'request "{page_url}" failed: {e}')
cursor.execute(
"UPDATE web_docs SET attempts=attempts+1 WHERE url = ?", (page_url,)
)
cursor.execute(
f"UPDATE web_docs SET status='failed' WHERE url = ? AND attempts>={max_attempts}",
(page_url,),
)
conn.commit()
continue

# 更新数据库 urls 列表, 来保存进度做到断点重试的功能, 无需持久化 visited, urls 等 python 脚本, 使得 interrupt exception 无关紧要 (因为数据库自带回滚, 无需担心访问到一半导致的错误)
new_links = []
for a_link in tqdm(soup.find_all("a"), desc=page_url):
href = str(a_link.get("href", ""))
if not href:
# link: "https://example.com" has no href attribute
logger.debug(f'link: "{a_link}" has no href attribute')
continue

next_url, frag = urldefrag(urljoin(page_url, href))
host = urlparse(next_url).hostname

if host != base_host:
# skip "" because "host1" not equal to "base_host"
logger.debug(
f'skip "{next_url}" because "{host}" not equal to "{base_host}"'
)
continue
new_links.append(next_url)

# save to database
cursor.execute(
"UPDATE web_docs SET content=?, status='done' WHERE url=?",
(html_content, page_url),
)
cursor.executemany(
"INSERT OR IGNORE INTO web_docs (url) VALUES (?)", [(u,) for u in new_links]
)
conn.commit()

logger.info("Success")

except KeyboardInterrupt:
conn.commit() # 中断瞬间前的已存页面不丢失
logger.info("Interrupted, progress is safe in sqlite.db")
finally:
conn.close()

或许任务队列也可以这么实现, 无需其他方法了.

  • Title: 网络爬虫
  • Author: Ivan
  • Created at : 2026-08-10 00:00:00
  • Updated at : 2026-10-23 18:02:31
  • Link: https://ivanfan-van.github.io/2026/08/10/note-2-seed-025/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
网络爬虫