在这一章中,我们将通过两个案例,展示如何编写实际项目中的爬虫。第一个案例是爬取新闻网站的爬虫,第二个案例是爬取电商网站商品信息的爬虫。这些案例将帮助我们将前面学到的知识应用到实际项目中。
案例1:新闻网站爬虫
在这个案例中,我们将编写一个爬取新闻网站文章信息的爬虫。我们以一个假设的新闻网站为例,抓取文章标题、作者、发布时间和内容。
步骤1:分析目标网站结构
假设目标新闻网站的结构如下:
- 文章列表页面:
http://news.example.com/page/1
- 文章详情页面:
http://news.example.com/article/123
步骤2:编写爬虫代码
python">import requests
from bs4 import BeautifulSoup
import csv# 文章列表页URL模板
base_url = "http://news.example.com/page/"# 爬取文章详情的函数
def fetch_article(url):response = requests.get(url)if response.status_code == 200:soup = BeautifulSoup(response.content, 'html.parser')title = soup.find('h1', class_='article-title').textauthor = soup.find('span', class_='article-author').textdate = soup.find('span', class_='article-date').textcontent = soup.find('div', class_='article-content').textreturn {'title': title,'author': author,'date': date,'content': content}else:return None# 爬取文章列表页的函数
def fetch_articles_from_page(page):url = f"{base_url}{page}"response = requests.get(url)articles = []if response.status_code == 200:soup = BeautifulSoup(response.content, 'html.parser')links = soup.find_all('a', class_='article-link')for link in links:article_url = link['href']article = fetch_article(article_url)if article:articles.append(article)return articles# 保存数据到CSV文件
def save_to_csv(articles, filename):with open(filename, 'w', newline='', encoding='utf-8') as csvfile:fieldnames = ['title', 'author', 'date', 'content']writer = csv.DictWriter(csvfile, fieldnames=fieldnames)writer.writeheader()for article in articles:writer.writerow(article)# 主程序
if __name__ == "__main__":all_articles = []for page in range(1, 6): # 假设要爬取前5页articles = fetch_articles_from_page(page)all_articles.extend(articles)save_to_csv(all_articles, 'news_articles.csv')print("新闻数据已保存到 news_articles.csv")
代码解释:
- 定义爬取函数:
fetch_article
函数负责爬取单篇文章的详情,fetch_articles_from_page
函数负责爬取文章列表页并提取文章链接。 - 保存数据到CSV文件:
save_to_csv
函数将爬取到的文章数据保存到CSV文件。 - 主程序: 爬取前5页的文章,保存数据到CSV文件。
案例2:电商网站爬虫
在这个案例中,我们将编写一个爬取电商网站商品信息的爬虫。我们以一个假设的电商网站为例,抓取商品名称、价格、评分和详情。
步骤1:分析目标网站结构
假设目标电商网站的结构如下:
- 商品列表页面:
http://ecommerce.example.com/page/1
- 商品详情页面:
http://ecommerce.example.com/product/123
步骤2:编写爬虫代码
python">import requests
from bs4 import BeautifulSoup
import csv# 商品列表页URL模板
base_url = "http://ecommerce.example.com/page/"# 爬取商品详情的函数
def fetch_product(url):response = requests.get(url)if response.status_code == 200:soup = BeautifulSoup(response.content, 'html.parser')name = soup.find('h1', class_='product-name').textprice = soup.find('span', class_='product-price').textrating = soup.find('div', class_='product-rating').textdetails = soup.find('div', class_='product-details').textreturn {'name': name,'price': price,'rating': rating,'details': details}else:return None# 爬取商品列表页的函数
def fetch_products_from_page(page):url = f"{base_url}{page}"response = requests.get(url)products = []if response.status_code == 200:soup = BeautifulSoup(response.content, 'html.parser')links = soup.find_all('a', class_='product-link')for link in links:product_url = link['href']product = fetch_product(product_url)if product:products.append(product)return products# 保存数据到CSV文件
def save_to_csv(products, filename):with open(filename, 'w', newline='', encoding='utf-8') as csvfile:fieldnames = ['name', 'price', 'rating', 'details']writer = csv.DictWriter(csvfile, fieldnames=fieldnames)writer.writeheader()for product in products:writer.writerow(product)# 主程序
if __name__ == "__main__":all_products = []for page in range(1, 6): # 假设要爬取前5页products = fetch_products_from_page(page)all_products.extend(products)save_to_csv(all_products, 'ecommerce_products.csv')print("商品数据已保存到 ecommerce_products.csv")
代码解释:
- 定义爬取函数:
fetch_product
函数负责爬取单个商品的详情,fetch_products_from_page
函数负责爬取商品列表页并提取商品链接。 - 保存数据到CSV文件:
save_to_csv
函数将爬取到的商品数据保存到CSV文件。 - 主程序: 爬取前5页的商品,保存数据到CSV文件。
结论
通过以上两个案例,我们展示了如何编写实际项目中的爬虫。第一个案例是爬取新闻网站文章信息,第二个案例是爬取电商网站商品信息。这些案例将帮助我们将前面学到的知识应用到实际项目中,并进一步提高我们的爬虫编写能力。在下一篇文章中,我们将探讨更多高级技术和优化方法。