使用Python实现一个简单的Web爬虫
在当今数据驱动的时代,网络爬虫(Web Crawler)技术已成为获取和分析数据的重要手段。本文将介绍如何使用 Python 编写一个简单的 Web 爬虫程序,用于从网页中提取信息,并将其存储为结构化数据。我们将使用 requests
和 BeautifulSoup
这两个流行的 Python 库来完成这项任务。
什么是Web爬虫?
Web爬虫是一种自动访问互联网上的网页并从中提取数据的程序。搜索引擎如 Google、Bing 等都依赖大规模的爬虫系统来索引全球网页内容。除了搜索引擎,爬虫还广泛应用于数据分析、价格监控、舆情监测等多个领域。
环境准备
在开始编写代码之前,请确保你的环境中安装了以下库:
pip install requests beautifulsoup4 lxml
requests:用于发送 HTTP 请求并获取网页内容。beautifulsoup4:用于解析 HTML 或 XML 文档。lxml:作为 BeautifulSoup 的解析器,速度快且功能强大。项目目标
我们将创建一个爬虫程序,目标是抓取 https://books.toscrape.com/ 上的所有图书名称及其评分等级,并将结果保存到 CSV 文件中。
步骤分解
步骤1:获取网页内容
我们首先使用 requests
获取网页的 HTML 内容:
import requestsurl = "https://books.toscrape.com/"response = requests.get(url)if response.status_code == 200: html_content = response.text print("成功获取网页内容")else: print(f"请求失败,状态码:{response.status_code}")
步骤2:解析HTML内容
接下来,我们使用 BeautifulSoup
来解析 HTML 并提取我们需要的信息。
from bs4 import BeautifulSoupsoup = BeautifulSoup(html_content, 'lxml')# 查找所有书籍条目books = soup.find_all('article', class_='product_pod')for book in books: title = book.h3.a['title'] rating_class = book.p['class'][1] # 评分等级在第二个类名中 print(f"书名:{title},评分:{rating_class}")
输出示例:
书名:A Light in the Attic,评分:Three书名:Moleskine Classic Notebook Soft Cover (XXL Size) Moleskine Pocket Ruled Notebook,评分:One...
步骤3:处理分页
网站通常会有多页内容。我们可以查找下一页链接并递归爬取所有页面:
def get_books_from_page(url): response = requests.get(url) if response.status_code != 200: return [] soup = BeautifulSoup(response.text, 'lxml') books = soup.find_all('article', class_='product_pod') for book in books: title = book.h3.a['title'] rating_class = book.p['class'][1] print(f"书名:{title},评分:{rating_class}") next_page = soup.find('li', class_='next') if next_page: next_url = url.rsplit('/', 1)[0] + '/' + next_page.find('a')['href'] get_books_from_page(next_url)get_books_from_page("https://books.toscrape.com/")
步骤4:保存数据到CSV文件
为了持久化存储这些数据,我们可以将它们保存到 CSV 文件中:
import csvdef save_books_to_csv(filename="books.csv"): with open(filename, mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(["Title", "Rating"]) def recursive_scrape(url): response = requests.get(url) if response.status_code != 200: return soup = BeautifulSoup(response.text, 'lxml') books = soup.find_all('article', class_='product_pod') for book in books: title = book.h3.a['title'] rating_class = book.p['class'][1] writer.writerow([title, rating_class]) next_page = soup.find('li', class_='next') if next_page: next_url = url.rsplit('/', 1)[0] + '/' + next_page.find('a')['href'] recursive_scrape(next_url) recursive_scrape("https://books.toscrape.com/")save_books_to_csv()print("数据已保存至 books.csv")
运行后会在当前目录生成一个名为 books.csv
的文件,内容如下:
Title,RatingA Light in the Attic,ThreeMoleskine Classic Notebook Soft Cover (XXL Size) Moleskine Pocket Ruled Notebook,One...
注意事项与反爬机制
虽然本项目是一个简单的爬虫,但在实际应用中需要注意以下几点:
User-Agent设置:很多网站会对没有 User-Agent 的请求进行屏蔽。你可以通过添加 headers 参数来模拟浏览器行为:
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'}response = requests.get(url, headers=headers)
设置延迟:频繁请求可能会导致 IP 被封禁,建议在每次请求之间加入适当的延迟:
import timetime.sleep(1) # 每次请求间隔1秒
遵守Robots协议:检查目标网站的 /robots.txt
文件,了解哪些页面允许爬取。
异常处理:增加 try-except 块以应对网络错误或页面结构变化。
扩展建议
多线程/异步爬虫:使用concurrent.futures
或 asyncio
提高爬取效率。使用代理服务器:避免IP被封,可使用代理池。数据清洗与分析:结合 pandas 对数据进一步处理和可视化。部署定时任务:使用 cron 或 Airflow 定时执行爬虫。总结
本文介绍了如何使用 Python 编写一个简单的 Web 爬虫,涵盖从网页抓取、数据解析到结果存储的完整流程。通过这个例子,你已经掌握了基本的爬虫开发技能。当然,真正的爬虫系统还需要考虑更多的健壮性和合规性问题。希望这篇文章能为你打开通向数据采集世界的大门。
附录:完整代码
import requestsfrom bs4 import BeautifulSoupimport csvimport timedef save_books_to_csv(filename="books.csv"): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36' } with open(filename, mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(["Title", "Rating"]) def recursive_scrape(url): time.sleep(1) response = requests.get(url, headers=headers) if response.status_code != 200: print(f"请求失败:{url}") return soup = BeautifulSoup(response.text, 'lxml') books = soup.find_all('article', class_='product_pod') for book in books: title = book.h3.a['title'] rating_class = book.p['class'][1] writer.writerow([title, rating_class]) next_page = soup.find('li', class_='next') if next_page: next_url = url.rsplit('/', 1)[0] + '/' + next_page.find('a')['href'] recursive_scrape(next_url) recursive_scrape("https://books.toscrape.com/")save_books_to_csv()print("数据已保存至 books.csv")
如果你对爬虫技术感兴趣,可以继续深入学习 Scrapy、Selenium、Playwright 等更高级的工具,以应对动态加载页面和复杂的反爬策略。