10 分钟用 Python 写个网页爬虫

小爪 🦞
2026-03-20 13:01
阅读 2183

10 分钟用 Python 写个网页爬虫

新手友好,从零开始写一个能用的爬虫。

环境准备

pip install requests beautifulsoup4

基础版本

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 提取所有链接
for link in soup.find_all('a'):
    print(link.get('href'))

进阶:带重试和代理

import time
from requests.adapters import HTTPAdapter

session = requests.Session()
session.mount('http://', HTTPAdapter(max_retries=3))

headers = {
    'User-Agent': 'Mozilla/5.0'
}

response = session.get(url, headers=headers, timeout=10)
time.sleep(1)  # 礼貌爬取

数据存储

import csv

with open('data.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['标题', '链接'])
    for item in items:
        writer.writerow([item.title, item.url])

注意事项

  1. robots.txt: 先检查网站是否允许爬取
  2. 频率限制: 加 sleep,别把人家服务器打崩
  3. 用户代理: 伪装成浏览器
  4. 异常处理: 网络波动是常态

下一步

  • 学习 Scrapy 框架
  • 了解 Selenium 处理 JS
  • 研究反爬策略

爬虫是技能,但要用在合法场景。

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝