在大数据时代,数据采集是开发者的必备技能之一,而Python凭借其简洁的语法和丰富的库(如requests
、BeautifulSoup
)成为爬虫开发的首选语言。本文将从零开始,带你一步步构建一个简单的网页数据采集系统,爬取目标网站的数据并保存为CSV文件。无论是新手还是有经验的开发者,都能从中收获实用技巧。欢迎在评论区分享你的爬虫经验!
确保已安装Python 3.x,并准备以下库:
pip install requests beautifulsoup4 pandas
本文以爬取「博客园」(https://www.cnblogs.com)热门文章标题和链接为例。注意:爬虫需遵守目标网站的robots.txt
协议,避免违反法律或道德规范。
使用requests
发送GET请求,获取目标网页的HTML源码:
import requests
url = "https://www.cnblogs.com"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
print("页面获取成功!")
else:
print(f"请求失败,状态码:{response.status_code}")
Tips:添加User-Agent
模拟浏览器请求,避免被网站屏蔽。
使用BeautifulSoup
提取热门文章的标题和链接:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# 定位文章列表区域(根据博客园HTML结构)
articles = soup.select(".post-item .post-item-title a")
data = []
for article in articles:
title = article.text.strip()
link = article["href"]
data.append({"title": title, "link": link})
解析说明:
.post-item-title a
是博客园热门文章的CSS选择器,可通过浏览器开发者工具(F12)查看具体结构将爬取结果保存为CSV文件:
import pandas as pd
df = pd.DataFrame(data)
df.to_csv("cnblogs_hot_articles.csv", index=False, encoding="utf-8-sig")
print("数据已保存至cnblogs_hot_articles.csv")
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 发送请求
url = "https://www.cnblogs.com"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
# 解析HTML
soup = BeautifulSoup(response.text, "html.parser")
articles = soup.select(".post-item .post-item-title a")
data = []
for article in articles:
title = article.text.strip()
link = article["href"]
data.append({"title": title, "link": link})
# 保存数据
df = pd.DataFrame(data)
df.to_csv("cnblogs_hot_articles.csv", index=False, encoding="utf-8-sig")
print("数据已保存至cnblogs_hot_articles.csv")
else:
print(f"请求失败,状态码:{response.status_code}")
time.sleep(random.uniform(1, 3))
避免频繁请求requests
的proxies
参数)对于JavaScript渲染的页面,可使用:
selenium
模拟浏览器操作playwright
支持多浏览器自动测试from collections import Counter
import matplotlib.pyplot as plt
words = " ".join(df["title"]).split()
word_freq = Counter(words).most_common(10)
plt.bar([w[0] for w in word_freq], [w[1] for w in word_freq])
plt.show()
robots.txt
协议asyncio
)通过本文实践,我们掌握了从网页请求到数据存储的完整爬虫开发流程。建议后续尝试: