浅学爬虫-案例

server/2024/10/20 11:38:27/

在这一章中,我们将通过两个案例,展示如何编写实际项目中的爬虫。第一个案例是爬取新闻网站的爬虫,第二个案例是爬取电商网站商品信息的爬虫。这些案例将帮助我们将前面学到的知识应用到实际项目中。

案例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")

代码解释:

  1. 定义爬取函数: fetch_article函数负责爬取单篇文章的详情,fetch_articles_from_page函数负责爬取文章列表页并提取文章链接。
  2. 保存数据到CSV文件: save_to_csv函数将爬取到的文章数据保存到CSV文件。
  3. 主程序: 爬取前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")

代码解释:

  1. 定义爬取函数: fetch_product函数负责爬取单个商品的详情,fetch_products_from_page函数负责爬取商品列表页并提取商品链接。
  2. 保存数据到CSV文件: save_to_csv函数将爬取到的商品数据保存到CSV文件。
  3. 主程序: 爬取前5页的商品,保存数据到CSV文件。
结论

通过以上两个案例,我们展示了如何编写实际项目中的爬虫。第一个案例是爬取新闻网站文章信息,第二个案例是爬取电商网站商品信息。这些案例将帮助我们将前面学到的知识应用到实际项目中,并进一步提高我们的爬虫编写能力。在下一篇文章中,我们将探讨更多高级技术和优化方法。


http://www.ppmy.cn/server/95434.html

相关文章

TCP 和 UDP 之间的区别?

从 连接,可靠性,传输方式等方面: TCP 是面向连接的协议,在发送数据的时候需要先通过 TCP 的三次握手,而 UDP 是无连接的协议,可以直接传输数据TCP 通过超时重传,流量控制和拥塞控制等方法保障了…

c#中的正则表达式和日期的使用(超全)

在 C# 中,正则表达式(Regular Expressions)是一种强大的文本处理工具,用于执行各种字符串搜索、替换和验证任务。以下是一些常用的正则表达式示例及其用途: 1. 邮箱地址验证 ​string emailPattern "^[^\s][^\…

24暑假算法刷题 | Day27 | 贪心算法 I | LeetCode 455. 分发饼干,376. 摆动序列,53. 最大子数组和

目录 455. 分发饼干题目描述题解 376. 摆动序列题目描述题解 53. 最大子数组和题目描述题解 455. 分发饼干 点此跳转题目链接 题目描述 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i&#x…

均匀线性阵列 (ULA) 的基础知识【附全部MATLAB代码】

微信公众号:EW Frontier QQ交流群:949444104 主要内容 介绍 均匀线性阵列 (ULA) 是沿直线等距分布的传感器元件的集合。最常见的传感器类型是偶极子天线,可以在空中发射和接收电磁波。其他类型的传感器包括可在空气中…

【C++程序设计】——利用数组处理批量数据(二)

👨‍💻个人主页:开发者-削好皮的Pineapple! 👨‍💻 hello 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅! 👨‍💻 本文由 削好皮的Pineapple! 原创 👨‍&#x1f4…

Python 如何进行自然语言处理(NLTK, SpaCy)

自然语言处理(Natural Language Processing, NLP)是计算机科学和人工智能的一个重要领域,旨在实现计算机对人类语言的理解和处理。在Python中,有许多工具和库可以用于自然语言处理,其中最流行的两个是NLTK(…

C#学习笔记20240730

文章目录 连接字符串连接字符串是什么?SQLServer连接字符串配置文件中存储异常 SqlCommandSqlCommand介绍重要属性创建 Command执行方法ExecuteNonQuery 连接字符串 连接字符串是什么? 字符串,一组被格式化的键值对,数据源在哪里…

本科阶段最后一次竞赛Vlog——2024年智能车大赛智慧医疗组准备全过程——3bin模型转化环境的准备

本科阶段最后一次竞赛Vlog——2024年智能车大赛智慧医疗组准备全过程——3bin模型转化环境的准备 ​ 今天给大家带来的是在上一期基础上最重要的一步,这个地方是我开始踩坑的开始。 ​ 当时一开始看教程,不知道怎么看到了高级进阶版。当时也是弄了好久…