当然可以!下面是《Python 数据爬取(爬虫):从零开始学会爬取网页数据》的完整教学,适合初学者从零入门,逐步掌握网页结构解析、反爬机制应对、数据提取与保存技巧。
📘 目录
- 什么是爬虫?Python 爬虫的基本流程
- 安装必要的爬虫库(requests、BeautifulSoup、lxml、selenium 等)
- 用 requests 获取网页内容
- 用 BeautifulSoup / lxml 解析网页结构
- 爬取实战案例一:豆瓣电影 Top250
- 应对反爬虫机制(Headers、延时、代理、验证码)
- 用 Selenium 爬取动态加载网站
- 爬虫数据保存为 CSV / Excel / 数据库
- 多线程爬虫与爬虫框架(Scrapy 简介)
- 爬虫合法性与道德问题
1. 什么是爬虫?Python 爬虫的基本流程
网页爬虫(Web Crawler)是自动访问网页并提取数据的程序。
爬虫基本流程:
- 发出请求:通过
requests.get()
向网页发送请求 - 获取响应:获取 HTML 页面内容
- 解析数据:使用
BeautifulSoup
、lxml
等解析网页结构 - 提取数据:通过标签和属性提取目标数据
- 存储数据:写入文件、Excel 或数据库
2. 安装必要库
pip install requests beautifulsoup4 lxml pandas selenium
注:
selenium
需要浏览器驱动(如 chromedriver),用于动态页面爬取。
3. 用 requests
获取网页内容
import requests
url = "https://movie.douban.com/top250"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.text[:500]) # 打印前500个字符
4. 用 BeautifulSoup
解析网页结构
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("span", class_="title")
for t in titles:
print(t.text)
5. 实战案例:爬取豆瓣电影 Top250
import time
import csv
with open("douban_top250.csv", mode="w", newline='', encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["排名", "电影名", "评分", "链接"])
for page in range(10):
url = f"https://movie.douban.com/top250?start={page*25}"
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, "html.parser")
movies = soup.find_all("div", class_="item")
for m in movies:
rank = m.find("em").text
name = m.find("span", class_="title").text
score = m.find("span", class_="rating_num").text
link = m.find("a")["href"]
writer.writerow([rank, name, score, link])
time.sleep(1) # 延迟防止被封
6. 应对反爬虫机制
技术/策略 | 作用 |
---|---|
修改 Headers | 模拟浏览器 |
加入延时 / 随机延时 | 防止高频访问封 IP |
使用代理 IP | 防止 IP 被封 |
Selenium + 手动滑块 | 绕过 JS 加载与验证码 |
使用验证码识别接口 | OCR(需额外服务) |
# 伪装浏览器
headers = {
"User-Agent": "Mozilla/5.0",
"Referer": "https://www.google.com"
}
7. 使用 Selenium 爬取动态网页
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.jd.com")
time.sleep(2)
search = driver.find_element(By.ID, "key")
search.send_keys("笔记本电脑")
search.submit()
time.sleep(5)
html = driver.page_source
driver.quit()
8. 数据保存
保存为 CSV:
import pandas as pd
df = pd.DataFrame(data_list)
df.to_csv("data.csv", index=False, encoding="utf-8")
保存为 Excel:
df.to_excel("data.xlsx", index=False)
保存到 SQLite:
import sqlite3
conn = sqlite3.connect("data.db")
df.to_sql("movies", conn, if_exists="replace", index=False)
9. 多线程与 Scrapy 框架(进阶)
简易多线程:
import threading
def crawl_page(url):
res = requests.get(url, headers=headers)
print(url, res.status_code)
urls = ["https://example.com/page1", "https://example.com/page2"]
threads = [threading.Thread(target=crawl_page, args=(url,)) for url in urls]
for t in threads:
t.start()
for t in threads:
t.join()
Scrapy 简介:
pip install scrapy
scrapy startproject myspider
Scrapy 是企业级高性能爬虫框架,支持异步、pipeline、多管道、自动去重等。
10. 爬虫合法性与道德建议
- 遵守网站
robots.txt
- 不采集用户隐私数据
- 尊重访问频率,避免 DDoS 行为
- 不用爬虫模拟账号攻击或刷票
发表回复