Python爬虫基础
Python爬虫是一种自动化程序,用于从网页上收集数据。主要依赖以下库:
- Requests:发送HTTP请求获取网页内容。
- BeautifulSoup:解析HTML或XML文档,提取数据。
- Scrapy:完整的爬虫框架,适合大规模数据抓取。
安装基础库:
pip install requests beautifulsoup4 scrapy
简单爬虫示例
使用Requests和BeautifulSoup抓取网页标题:
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)
处理动态内容
动态加载的网页(如JavaScript渲染)需使用Selenium或Playwright:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://example.com')
print(driver.title)
driver.quit()
数据存储
爬取的数据可保存为CSV、JSON或数据库:
import csv
data = [['标题', '链接'], ['Example', 'https://example.com']]
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
遵守Robots协议
检查目标网站的robots.txt(如https://example.com/robots.txt),避免爬取禁止的目录或高频访问。
反爬虫策略应对
- User-Agent轮换:模拟不同浏览器访问。
- IP代理池:避免IP被封禁。
- 请求间隔:添加
time.sleep()降低请求频率。
示例设置User-Agent:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
Scrapy框架入门
创建Scrapy项目:
scrapy startproject myproject
cd myproject
scrapy genspider example example.com
修改spiders/example.py:
import scrapy
class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['https://example.com']
def parse(self, response):
yield {'title': response.css('title::text').get()}
运行爬虫:
scrapy crawl example -o output.json
高级应用
- 分布式爬虫:使用Scrapy-Redis实现多机协作。
- 验证码识别:集成第三方工具如Tesseract-OCR。
- Headless浏览器:通过Pyppeteer无界面抓取动态内容。

被折叠的 条评论
为什么被折叠?



