使用Python实现一个简单的Web爬虫
在当今数据驱动的世界中,网络爬虫(Web Crawler)已经成为获取互联网信息的重要工具。本文将介绍如何使用 Python 编写一个简单的 Web 爬虫,并从网页中提取有用的数据。我们将使用 requests
和 BeautifulSoup
这两个常用的库来完成这个任务。
1. 环境准备
在开始之前,请确保你的开发环境中已经安装了以下 Python 库:
requests
:用于发送 HTTP 请求。beautifulsoup4
:用于解析 HTML 文档。lxml
(可选):用于更快速地解析 HTML。你可以使用以下命令安装这些库:
pip install requests beautifulsoup4 lxml
2. 基本概念
2.1 Web 爬虫的工作原理
Web 爬虫的基本工作流程如下:
发送 HTTP 请求到目标网站。接收服务器返回的 HTML 内容。解析 HTML,提取所需的数据。存储或处理提取到的数据。2.2 Robots 协议
在编写爬虫程序时,务必遵守目标网站的 robots.txt
文件中的规定,尊重网站的爬取限制。例如,访问 https://example.com/robots.txt
可以查看该网站允许哪些路径被爬取。
3. 实现一个简单的 Web 爬虫
我们将编写一个爬虫程序,从 https://books.toscrape.com/ 网站抓取书籍信息,包括书名、价格和评分。
3.1 发送请求并获取网页内容
首先,我们使用 requests
库发送一个 GET 请求来获取网页内容。
import requestsurl = "https://books.toscrape.com/"response = requests.get(url)if response.status_code == 200: html_content = response.textelse: print("Failed to retrieve the webpage.")
3.2 解析 HTML 内容
接下来,我们使用 BeautifulSoup
来解析 HTML 并提取书籍信息。
from bs4 import BeautifulSoupsoup = BeautifulSoup(html_content, 'html.parser')# 查找所有书籍条目books = soup.find_all('article', class_='product_pod')for book in books: title = book.h3.a['title'] price = book.find('p', class_='price_color').text rating_class = book.p['class'][1] # 获取星级评价类名 print(f"Title: {title}, Price: {price}, Rating: {rating_class}")
输出示例:
Title: A Light in the Attic, Price: £51.77, Rating: ThreeTitle: Fifty Shades of Grey, Price: £52.12, Rating: Two...
3.3 将数据保存为 CSV 文件
我们可以将提取到的数据保存为 CSV 文件,便于后续分析。
import csvwith open('books.csv', mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['Title', 'Price', 'Rating']) for book in books: title = book.h3.a['title'] price = book.find('p', class_='price_color').text rating_class = book.p['class'][1] writer.writerow([title, price, rating_class])
运行后将在当前目录下生成一个名为 books.csv
的文件。
4. 处理分页
为了抓取整个网站的所有书籍,我们需要处理分页功能。每一页都有一个“next”按钮链接到下一页。
def get_books_from_page(url): response = requests.get(url) if response.status_code != 200: return None, None soup = BeautifulSoup(response.text, 'html.parser') books = soup.find_all('article', class_='product_pod') next_page = soup.find('li', class_='next') next_page_url = next_page.a['href'] if next_page else None return books, next_page_urlbase_url = "https://books.toscrape.com/"current_url = base_urlall_books = []while current_url: print(f"Scraping page: {current_url}") books, next_page = get_books_from_page(current_url) if not books: break all_books.extend(books) current_url = base_url + next_page if next_page else None# 保存所有页面的数据with open('all_books.csv', mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['Title', 'Price', 'Rating']) for book in all_books: title = book.h3.a['title'] price = book.find('p', class_='price_color').text rating_class = book.p['class'][1] writer.writerow([title, price, rating_class])
5. 设置请求头与延迟
为了避免被网站封禁,我们可以设置请求头模拟浏览器访问,并添加随机延迟。
import timeimport randomfrom fake_useragent import UserAgentua = UserAgent()headers = { 'User-Agent': ua.random}def get_books_from_page(url): time.sleep(random.uniform(1, 3)) # 随机等待1~3秒 response = requests.get(url, headers=headers) if response.status_code != 200: return None, None soup = BeautifulSoup(response.text, 'html.parser') books = soup.find_all('article', class_='product_pod') next_page = soup.find('li', class_='next') next_page_url = next_page.a['href'] if next_page else None return books, next_page_url
别忘了安装 fake_useragent
:
pip install fake-useragent
6. 异常处理与健壮性
在实际应用中,网络请求可能会失败,因此我们需要加入异常处理机制。
def get_books_from_page(url): try: time.sleep(random.uniform(1, 3)) response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # 抛出HTTP错误 except requests.exceptions.RequestException as e: print(f"Request failed: {e}") return None, None soup = BeautifulSoup(response.text, 'html.parser') books = soup.find_all('article', class_='product_pod') next_page = soup.find('li', class_='next') next_page_url = next_page.a['href'] if next_page else None return books, next_page_url
7. 总结
通过本文,你学会了如何使用 Python 编写一个基本的 Web 爬虫程序,包括:
发送 HTTP 请求;使用 BeautifulSoup 解析 HTML;提取网页中的数据;分页爬取;设置请求头和延迟;异常处理。当然,这只是 Web 爬虫的基础。在实际项目中,你可能还需要处理 JavaScript 渲染的内容(可以使用 Selenium 或 Playwright)、登录认证、反爬策略等高级功能。
希望这篇文章对你理解 Web 爬虫技术有所帮助!如果你对某个具体功能感兴趣,欢迎留言继续探讨。