-
使用python scrapy框架抓取cnblog 的文章内容
- 网站名称:使用python scrapy框架抓取cnblog 的文章内容
- 网站分类:技术文章
- 收录时间:2025-08-02 15:53
- 网站地址:
“使用python scrapy框架抓取cnblog 的文章内容” 网站介绍
scrapy 的文档请移驾到
http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/install.html
1、准备工作
安装python 、Spyder 、scrapy 如果想要数据直接入mysql 还需要安装python的 MySQLdb 依赖包
本人mac操作系统 安装MySQLdb的时候出现了些小问题 最后是重装了openssl 才通过的
Spyder 是编写python的ide
2、新建项目
cd /usr/local/var/www/python
执行 scrapy startproject myblog 则新建了一个名称为myblog 的项目,执行完成后 你的python文件夹就出现了myblog文件夹了
cnblog_spider.py 是后来我新建的 后缀.pyc 是执行python后的编译的文件 其他的都是执行创建项目后就自动生成的文件了
3、编写爬虫脚本 cnblog_spider.py
分析cnblog的网站 使用scrapy shell
http://www.cnblogs.com/threemore/
使用google浏览器 找到你想要抓取的数据 话不多说 直接上代码,我抓取了cnblog文章的标题,链接 时间,文章的id,正文内容
# -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from myblog.items import MyblogItem import scrapy import re #SITE_URL = 'http://www.cnblogs.com/threemore/' #抓取在cnblog中的文章 class CnblogSpider(Spider): #抓取名称 执行命令的时候后面的名称 scrapy crawl cnblog 中的cnblog 就是在这里定义的 name ='cnblog' allow_domains = ["cnblogs.com"] #定义抓取的网址 start_urls = [ 'http://www.cnblogs.com/threemore/' ] #执行函数 def parse(self,response): sel = Selector(response) self.log("begins % s" % response.url) article_list = sel.css('div.postTitle').xpath('a') #抓取列表里面的内容也地址后循环抓取列表的内容页面数据 for article in article_list: url = article.xpath('@href').extract[0] self.log("list article url: % s" % url) #继续抓取内容页数据 yield scrapy.Request(url,callback=self.parse_content) #如果有下一页继续抓取数据 next_pages = sel.xpath('//*[@id="nav_next_page"]/a/@href') if next_pages : next_page = next_pages.extract[0] #print next_page self.log("next_page: % s" % next_page) #自己调用自己 类似php 函数的当中的递归 yield scrapy.Request(next_page,callback=self.parse) #内容页抓取 def parse_content(self,response): self.log("detail views: % s" % response.url) #定义好的item 只需要在items 文件中定义抓取过来的数据对应的字段 item = MyblogItem #xpath 寻找需要在页面中抓取的数据 item['link'] = response.url #正则匹配出文章在cnblog中的id m = re.search(r"([0-9])+", item['link']) if m: item['aid'] = m.group(0) else: item['aid'] = 0; item['title'] = response.xpath('//*[@id="cb_post_title_url"]/text').extract[0] item['content'] = response.xpath('//*[@id="cnblogs_post_body"]').extract[0] item['date'] = response.xpath('//*[@id="post-date"]').extract #print item['content'] yield item
4、数据入库
编写管道程序pipelines.py,管道就是存储数据使用的 爬虫文件最后yield 的item 会将数据给到pipelines.py 这个文件
为了测试和正式环境的方便 我就配置了两份mysql的登陆信息
每次执行前 都将即将入库的数据表给清空了一次 防止重复采集 ,直接看代码
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html #需要在setting.py文件中设置ITEM_PIPELINES 将前面的注释打开配置成当前的文件即可 #当前的管道就是这么配置 'myblog.pipelines.MyblogPipeline': 300, import MySQLdb,datetime DEBUG = True #定义测试环境和正式环境中的mysql if DEBUG: dbuser = 'root' dbpass = 'root' dbname = 'test' dbhost = '127.0.0.1' dbport = '3306' else: dbuser = 'root' dbpass = 'root' dbname = 'test' dbhost = '127.0.0.1' dbport = '3306' class MyblogPipeline(object): #初始化 链接数据库 def __init__(self): self.conn = MySQLdb.connect(user=dbuser, passwd=dbpass, db=dbname, host=dbhost, charset="utf8", use_unicode=True) self.cursor = self.conn.cursor self.cursor.execute('truncate table test_cnbog') self.conn.commit #执行sql语句 def process_item(self, item, spider): try: self.cursor.execute("""INSERT INTO test_cnbog (title, link, aid,content,date) VALUES (%s,%s,%s,%s,%s)""", ( item['title'].encode('utf-8'), item['link'].encode('utf-8'), item['aid'], item['content'].encode('utf-8'), datetime.datetime.now, ) ) self.conn.commit except MySQLdb.Error, e: print u'Error %d: $s' % (e.args[0],e.args[1]) return item
5、配置setting.py
开启入库的配置
找到 ITEM_PIPELINES 将前面的注释去掉 看到代码上面的注释的链接了么 直接访问看下是干啥的就行了 官方网站上看实例好像是将数据写入到monge里面去了
本人对monge 不熟悉 直接放到mysql去了 大致意思就是说pipelines.py 这个文件就是讲你采集的数据存放在什么地方
# Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'myblog.pipelines.MyblogPipeline': 300, }
6、执行采集
在项目的文件夹下面执行 :scrapy crawl myblog
特意将crawl 拿百度翻译看了下 啥意思 原来就是“爬行”
最后展示下采集回来的数据
15条没有采集到数据 aid 程序就是拿正则随便处理了下
更多相关网站
- TikTok Shop Enters Japan, Sparking Fresh Competition in Global E-Commerce
- China-Serbia forum highlights cooperation, civilizational dialogue
- 一文搭建智能问答聊天室(智能问答系统功能)
- 30天学会Python编程:18. Python数据库编程入门
- 亲身经历,对Gemini cli佩服的五体投地,太强了
- 莫祖永发明的世界身份证如何实现全球八十亿人民皆成为世界公民?
- 石浩双色球2025084期:精选6+1红球三胆20 21 24缩水倍投
- Boao Forum 2025: Why China's AI ambitions matter to the world
- CBN Special丨A modern cyber-Exodus: Why “TikTok refugees” flee to Xiaohongshu and what’s next?
- 'AI Godfather' Geoffrey Hinton Raises Alarm on AI Takeover Risks at WAIC Shanghai
- Thinkphp5.0极速搭建restful风格接口层
- K3s禁用Service Load Balancer,解决获取浏览器IP不正确问题
- 「python小脚本」监听日志文件异常数据发送告警短信
- 'Rebalancing' doesn't benefit Sino-EU ties
- Recasting civilizational dialogue in digital age: Harmony amid diversity
- MySql底层索引与数据优化「上篇」
- Android IPC 进程间通信全总结与选型指南
- Android数据库相关整理(android数据库的特点)
- 最近发表
-
- TikTok Shop Enters Japan, Sparking Fresh Competition in Global E-Commerce
- China-Serbia forum highlights cooperation, civilizational dialogue
- 一文搭建智能问答聊天室(智能问答系统功能)
- 30天学会Python编程:18. Python数据库编程入门
- 亲身经历,对Gemini cli佩服的五体投地,太强了
- 莫祖永发明的世界身份证如何实现全球八十亿人民皆成为世界公民?
- 使用python scrapy框架抓取cnblog 的文章内容
- 石浩双色球2025084期:精选6+1红球三胆20 21 24缩水倍投
- Boao Forum 2025: Why China's AI ambitions matter to the world
- CBN Special丨A modern cyber-Exodus: Why “TikTok refugees” flee to Xiaohongshu and what’s next?
- 标签列表
-
- mydisktest_v298 (35)
- sql 日期比较 (33)
- document.appendchild (35)
- 头像打包下载 (35)
- 二调符号库 (23)
- acmecadconverter_8.52绿色版 (25)
- 梦幻诛仙表情包 (36)
- 魔兽模型 (23)
- java面试宝典2019pdf (26)
- disk++ (30)
- 加密与解密第四版pdf (29)
- iteye (26)
- parsevideo (22)
- centos7.4下载 (32)
- intouch2014r2sp1永久授权 (33)
- usb2.0-serial驱动下载 (24)
- jdk1.8.0_191下载 (27)
- axure9注册码 (30)
- virtualdrivemaster (26)
- 数据结构c语言版严蔚敏pdf (25)
- 兔兔工程量计算软件下载 (27)
- 代码整洁之道 pdf (26)
- ccproxy破解版 (31)
- aida64模板 (28)
- contentvalues (23)