当前位置: 首页 > article >正文

Scrapy爬取heima论坛所有页面内容并保存到MySQL数据库中

 前期准备:

Scrapy入门_win10安装scrapy-CSDN博客

新建 Scrapy项目

scrapy startproject mySpider   # 项目名为mySpider

进入到spiders目录

 cd mySpider/mySpider/spiders

创建爬虫

 scrapy genspider heima  bbs.itheima.com      # 爬虫名为heima ,爬取域为bbs.itheima.com

 制作爬虫

items.py:

import scrapyclass heimaItem(scrapy.Item):title = scrapy.Field()url = scrapy.Field()

heima.py:

import scrapy
from scrapy.selector import Selector
from mySpider.items import heimaItemclass HeimaSpider(scrapy.Spider):name = 'heima'allowed_domains = ['bbs.itheima.com']start_urls = ['http://bbs.itheima.com/forum-425-1.html']def parse(self, response):print('response.url: ', response.url)selector = Selector(response)node_list = selector.xpath("//th[@class='new forumtit'] | //th[@class='common forumtit']")for node in node_list:# 文章标题title = node.xpath('./a[1]/text()')[0].extract()# 文章链接url = node.xpath('./a[1]/@href')[0].extract()# 创建heimaItem类item = heimaItem()item['title'] = titleitem['url'] = urlyield item# 获取下一页的链接if '下一页' in response.text:next_url = selector.xpath("//a[@class='nxt']/@href").extract()[0]yield scrapy.Request(next_url, callback=self.parse)

连接MySQL数据库并保存数据

首先需要在数据库中(使用workbench或者shell)创建数据库heima_db(如果不存在):

CREATE DATABASE IF NOT EXISTS heima_db;

pipelines.py:

from itemadapter import ItemAdapter
# 需要在终端中安装pymysql包:  pip install pymysql
import pymysqlclass MyspiderPipeline:def open_spider(self, spider):# 简单直接的MySQL连接self.connection = pymysql.connect(host='localhost',user='root',password='修改为自己的数据库密码',db='heima_db',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)self.cursor = self.connection.cursor()# 创建表(如果不存在)self.cursor.execute("""CREATE TABLE IF NOT EXISTS heima_news (id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),url VARCHAR(512),create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")# 清空现有数据self.cursor.execute("TRUNCATE TABLE heima_news") # 用于快速清空heima_news表中的所有数据。self.connection.commit()print("爬虫启动,数据库已准备就绪")# Scrapy会自动调用 process_item() 方法处理每一个抓取到的 item。# 每生成一个item(例如在爬虫的 parse 方法中 yield 一个item),Scrapy就会调用一次这个方法。def process_item(self, item, spider):# 插入数据self.cursor.execute("INSERT INTO heima_news (title, url) VALUES (%s, %s)",(item['title'], item['url']))self.connection.commit()return item# 当爬虫处理完所有 start_urls 和后续发现的链接# 没有更多请求需要处理时,此函数会被调用def close_spider(self, spider):# 显示数据数量self.cursor.execute("SELECT COUNT(*) AS total FROM heima_news")result = self.cursor.fetchone()print("爬取结束,result为:", result)print("爬取结束,数据库中一共保存的记录数为:", result['total'])# 关闭连接self.cursor.close()self.connection.close()

settings.py,解开ITEM_PIPELINES的注释,并修改其内容:

ITEM_PIPELINES = {

   "mySpider.pipelines.MyspiderPipeline": 300,

}

运行

在终端转到 mySpider/mySpider文件夹,根据你自己的路径写:

cd mySpider/mySpider

在终端中运行:

scrapy crawl heima -s LOG_ENABLED=False

结果

数据库信息:

http://www.lryc.cn/news/2384322.html

相关文章:

  • HarmonyOS NEXT~鸿蒙系统下的Cordova框架应用开发指南
  • com.alibaba.fastjson2 和com.alibaba.fastjson 区别
  • 探索数据结构的时间与空间复杂度:编程世界的效率密码
  • std::ranges::views::stride 和 std::ranges::stride_view
  • 了解Android studio 初学者零基础推荐(2)
  • 矩阵短剧系统:如何用1个后台管理100+小程序?技术解析与实战应用
  • C# 初学者的 3 种重构模式
  • MySQL 数据类型深度全栈实战,天花板玩法层出不穷!
  • 前端vscode学习
  • 自动驾驶传感器数据处理:Python 如何让无人车更智能?
  • 从电商角度设计大模型的 Prompt
  • 利用 SQL Server 作业实现异步任务处理:一种简化系统架构的实践方案
  • 平安健康2025年一季度深耕医养,科技赋能见成效
  • Index-AniSora技术升级开源:动漫视频生成强化学习
  • LLVM编译C++测试
  • ubuntu24.04+RTX5090D 显卡驱动安装
  • MATLAB贝叶斯超参数优化LSTM预测设备寿命应用——以航空发动机退化数据为例
  • 鸿蒙应用开发:Navigation组件使用流程
  • javaweb的拦截功能,自动跳转登录页面
  • 【Linux】系统在输入密码后进入系统闪退锁屏界面
  • 当物联网“芯”闯入纳米世界:ESP32-S3驱动的原子力显微镜能走多远?
  • 微信小程序webview与VUE-H5实时通讯,踩坑无数!亲测可实现
  • Web请求与相应
  • LeetCode222_完全二叉树的结点个数
  • STM32之温湿度传感器(DHT11)
  • 在微创手术中使用Kinova轻型机械臂进行多视图图像采集和3D重建
  • 2025版 JavaScript性能优化实战指南从入门到精通
  • FluxCD入门操作文档
  • DOM API-JS通过文档对象树操作Doc和CSS
  • 实现了TCP的单向通信