编写一个爬虫来实时获取某个平台的商品价格是一项实用的任务,可以帮助用户了解市场动态或监控价格变化。以下是一个简单的爬虫示例,使用 Python 的 requests
和 BeautifulSoup
库来抓取商品价格。为了演示,我将以一个假设的电商网站为例,具体步骤如下:
一、准备工作
- 安装必要的库
确保你的环境中已经安装了 requests
和 BeautifulSoup
。如果没有,可以通过以下命令安装:
bash
Copy code
pip install requests beautifulsoup4
- 选择目标网站
在开始编写爬虫之前,选择一个你想要爬取的电商网站,并确认其允许爬虫访问(查看 robots.txt
文件)。本示例中,我们将使用假设的网站 example.com/product
。
二、编写爬虫
以下是一个简单的爬虫示例,抓取指定商品的价格信息。
python
Copy code
import requests from bs4 import BeautifulSoup # 目标商品的URL url = 'https://example.com/product' def get_product_price(url): # 发起请求 try: response = requests.get(url) response.raise_for_status() # 检查请求是否