新浪网分类资讯爬虫

爬取新浪网导航页所有下所有大类、小类、小类里的子链接,以及子链接页面的新闻内容。

效果演示图:

items.py

import scrapy
import sys
reload(sys)
sys.setdefaultencoding("utf-8") class SinaItem(scrapy.Item):
# 大类的标题 和 url
parentTitle = scrapy.Field()
parentUrls = scrapy.Field() # 小类的标题 和 子url
subTitle = scrapy.Field()
subUrls = scrapy.Field() # 小类目录存储路径
subFilename = scrapy.Field() # 小类下的子链接
sonUrls = scrapy.Field() # 文章标题和内容
head = scrapy.Field()
content = scrapy.Field()

spiders/sina.py

# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- from Sina.items import SinaItem
import scrapy
import os import sys
reload(sys)
sys.setdefaultencoding("utf-8") class SinaSpider(scrapy.Spider):
name= "sina"
allowed_domains= ["sina.com.cn"]
start_urls= [
"http://news.sina.com.cn/guide/"
] def parse(self, response):
items= []
# 所有大类的url 和 标题
parentUrls = response.xpath('//div[@id=\"tab01\"]/div/h3/a/@href').extract()
parentTitle = response.xpath("//div[@id=\"tab01\"]/div/h3/a/text()").extract() # 所有小类的ur 和 标题
subUrls = response.xpath('//div[@id=\"tab01\"]/div/ul/li/a/@href').extract()
subTitle = response.xpath('//div[@id=\"tab01\"]/div/ul/li/a/text()').extract() #爬取所有大类
for i in range(0, len(parentTitle)):
# 指定大类目录的路径和目录名
parentFilename = "./Data/" + parentTitle[i] #如果目录不存在,则创建目录
if(not os.path.exists(parentFilename)):
os.makedirs(parentFilename) # 爬取所有小类
for j in range(0, len(subUrls)):
item = SinaItem() # 保存大类的title和urls
item['parentTitle'] = parentTitle[i]
item['parentUrls'] = parentUrls[i] # 检查小类的url是否以同类别大类url开头,如果是返回True (sports.sina.com.cn 和 sports.sina.com.cn/nba)
if_belong = subUrls[j].startswith(item['parentUrls']) # 如果属于本大类,将存储目录放在本大类目录下
if(if_belong):
subFilename =parentFilename + '/'+ subTitle[j]
# 如果目录不存在,则创建目录
if(not os.path.exists(subFilename)):
os.makedirs(subFilename) # 存储 小类url、title和filename字段数据
item['subUrls'] = subUrls[j]
item['subTitle'] =subTitle[j]
item['subFilename'] = subFilename items.append(item) #发送每个小类url的Request请求,得到Response连同包含meta数据 一同交给回调函数 second_parse 方法处理
for item in items:
yield scrapy.Request( url = item['subUrls'], meta={'meta_1': item}, callback=self.second_parse) #对于返回的小类的url,再进行递归请求
def second_parse(self, response):
# 提取每次Response的meta数据
meta_1= response.meta['meta_1'] # 取出小类里所有子链接
sonUrls = response.xpath('//a/@href').extract() items= []
for i in range(0, len(sonUrls)):
# 检查每个链接是否以大类url开头、以.shtml结尾,如果是返回True
if_belong = sonUrls[i].endswith('.shtml') and sonUrls[i].startswith(meta_1['parentUrls']) # 如果属于本大类,获取字段值放在同一个item下便于传输
if(if_belong):
item = SinaItem()
item['parentTitle'] =meta_1['parentTitle']
item['parentUrls'] =meta_1['parentUrls']
item['subUrls'] = meta_1['subUrls']
item['subTitle'] = meta_1['subTitle']
item['subFilename'] = meta_1['subFilename']
item['sonUrls'] = sonUrls[i]
items.append(item) #发送每个小类下子链接url的Request请求,得到Response后连同包含meta数据 一同交给回调函数 detail_parse 方法处理
for item in items:
yield scrapy.Request(url=item['sonUrls'], meta={'meta_2':item}, callback = self.detail_parse) # 数据解析方法,获取文章标题和内容
def detail_parse(self, response):
item = response.meta['meta_2']
content = ""
head = response.xpath('//h1[@id=\"main_title\"]/text()')
content_list = response.xpath('//div[@id=\"artibody\"]/p/text()').extract() # 将p标签里的文本内容合并到一起
for content_one in content_list:
content += content_one item['head']= head
item['content']= content yield item

pipelines.py

from scrapy import signals
import sys
reload(sys)
sys.setdefaultencoding("utf-8") class SinaPipeline(object):
def process_item(self, item, spider):
sonUrls = item['sonUrls'] # 文件名为子链接url中间部分,并将 / 替换为 _,保存为 .txt格式
filename = sonUrls[7:-6].replace('/','_')
filename += ".txt" fp = open(item['subFilename']+'/'+filename, 'w')
fp.write(item['content'])
fp.close() return item

settings.py

BOT_NAME = 'Sina'

SPIDER_MODULES = ['Sina.spiders']
NEWSPIDER_MODULE = 'Sina.spiders' ITEM_PIPELINES = {
'Sina.pipelines.SinaPipeline': 300,
} LOG_LEVEL = 'DEBUG'

在项目根目录下新建main.py文件,用于调试

from scrapy import cmdline
cmdline.execute('scrapy crawl sina'.split())

执行程序

py2 main.py

爬虫框架Scrapy之案例二的更多相关文章

  1. Python爬虫框架Scrapy实例(二)

    目标任务:使用Scrapy框架爬取新浪网导航页所有大类.小类.小类里的子链接.以及子链接页面的新闻内容,最后保存到本地. 大类小类如下图所示: 点击国内这个小类,进入页面后效果如下图(部分截图): 查 ...

  2. 爬虫框架Scrapy之案例三图片下载器

    items.py class CoserItem(scrapy.Item): url = scrapy.Field() name = scrapy.Field() info = scrapy.Fiel ...

  3. 爬虫框架Scrapy之案例一

    阳光热线问政平台 http://wz.sun0769.com/index.php/question/questionType?type=4 爬取投诉帖子的编号.帖子的url.帖子的标题,和帖子里的内容 ...

  4. 小白学 Python 爬虫(34):爬虫框架 Scrapy 入门基础(二)

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  5. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

  6. 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...

  7. 网络爬虫框架Scrapy简介

    作者: 黄进(QQ:7149101) 一. 网络爬虫 网络爬虫(又被称为网页蜘蛛,网络机器人),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本:它是一个自动提取网页的程序,它为搜索引擎从万维 ...

  8. 小白学 Python 爬虫(35):爬虫框架 Scrapy 入门基础(三) Selector 选择器

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  9. 小白学 Python 爬虫(36):爬虫框架 Scrapy 入门基础(四) Downloader Middleware

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

随机推荐

  1. git学习(7)标签管理

    git学习(7)标签管理 1. 建立标签 在发布版本时候,我们通常会在版本库中打一个标签,这样就唯一确定了打标签的版本,有点像个里程碑,这里会有一个指向某个commit的指针 打标签很简单,首先切换到 ...

  2. c# 下三角实现 九九乘法口诀表

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hell ...

  3. wcur LOCATE +

    w字符串处理 DROP PROCEDURE IF EXISTS w_unique; DELIMITER /w/ CREATE PROCEDURE w_unique() BEGIN DECLARE do ...

  4. webpack4学习笔记(二)

    webpack打包各种javascript文件 (本文只是提供一个学习记录,大部分内容来自网络) 一,打包js文件和es6代码 1,webpack命令打包js文件 Tip: 在webpack4.x之前 ...

  5. 设计模式之Singleton模式

    当程序运行时,有时会希望在程序中,只能存在一个实例,为了达到目的,所以设计了Singleton模式,即单例模式. 单例模式的特征: 想确保任何情况下只存在一个实例 想在程序上表现出只存在一个实例 示例 ...

  6. XAF 如何从Excel复制多个单元格内容到GridView(收藏)

    XAF 如何从Excel复制多个单元格内容到GridView 2012年04月11日 ⁄ 综合 ⁄ 共 10998字 ⁄ 字号 小 中 大 ⁄ 评论关闭 how to paste some excel ...

  7. Spring Data之Hello World

    1. 概述 SpringData : 注意目标是使数据库的访问变得方便快捷;支持NoSQL和关系数据存储; 支持NoSQL存储: MongoDB(文档数据库) Neo4j(图形数据库) Redis(键 ...

  8. Ubuntu 12.04安装Google Chrome(转)

    下载google chrome deb包,下载地址:https://www.google.com/chrome/browser/desktop/index.html,google的网站被墙了,如果你下 ...

  9. linux定时任务常用命令大全

    脚本中时间戳 TIMESTAMP=`date +%Y%m%d%H%M%S`

  10. Mysql索引长度和区分度

    首先  索引长度和区分度是相互矛盾的, 索引长度太短,那么区分度就很低,吧索引长度加长,区分度就高,但是索引也是要占内存的,所以我们需要找到一个平衡点: 那么这个平衡点怎么来定? 比如用户表有个字段 ...