目的:爬取阳光热线问政平台问题反映每个帖子里面的标题、内容、编号和帖子url

CrawlSpider版流程如下:

  1. 创建爬虫项目dongguang

    scrapy startproject dongguang
    
  2. 设置items.py文件

    
    # -*- coding: utf-8 -*-import scrapyclass NewdongguanItem(scrapy.Item):# 每页的帖子链接url = scrapy.Field()# 帖子标题title = scrapy.Field()# 帖子编号number = scrapy.Field()# 帖子内容content = scrapy.Field()
    
  3. 在spiders目录里面,创建并编写爬虫文件sun.py

    
    # -*- coding: utf-8 -*-import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    from dongguan.items import DongguanItemclass SunSpider(CrawlSpider):name = 'dg'allowed_domains = ['wz.sun0769.com']start_urls = ['http://wz.sun0769.com/html/top/report.shtml']# rules是Rule的集合,每个rule规则同时执行。另外,如果发现web服务器有反爬虫机制如返回一个假的url,则可以使用Rule里面的参数process_links调用一个自编函数来处理url后返回一个真的urlrules = (# 每个url都有一个独一无二的指纹,每个爬虫项目都有一个去重队列# Rule里面没有回调函数,则默认对匹配的链接要跟进,就是对匹配的链接在进行请求获取响应后对响应里面匹配的链接继续跟进,只不过没有回调函数对响应数据进行处理# Rule(LinkExtractor(allow="page="))如果设置为follow=False,则不会跟进,只显示当前页面匹配的链接。如设置为follow=True,则会对每个匹配的链接发送请求获取响应进而从每个响应里面再次匹配跟进,直至没有。python递归深度默认为不超过1000,否则会报异常Rule(LinkExtractor(allow="page=")),Rule(LinkExtractor(allow='http://wz.sun0769.com/html/question/\d+/\d+.shtml'),callback='parse_item'))def parse_item(self, response):print(response.url)item = DongguanItem()item['url'] = response.urlitem['title'] = response.xpath('//div[@class="pagecenter p3"]//strong/text()').extract()[0]item['number'] = response.xpath('//div[@class="pagecenter p3"]//strong/text()').extract()[0].split(' ')[-1].split(':')[-1]if len(response.xpath('//div[@class="contentext"]')) == 0:item['content'] = ''.join(response.xpath('//div[@class="c1 text14_2"]/text()').extract())else:item['content'] = ''.join(response.xpath('//div[@class="contentext"]/text()').extract())yield item
    
  4. 编写管道pipelines.py文件

    
    # -*- coding: utf-8 -*-import jsonclass DongguanPipeline(object):def __init__(self):self.file = open('dongguan.json','w')def process_item(self, item, spider):content = json.dumps(dict(item),ensure_ascii=False).encode('utf-8') + '\n'self.file.write(content)return itemdef closespider(self):self.file.close()
    
  5. 编写settings.py文件

    
    # -*- coding: utf-8 -*-BOT_NAME = 'dongguan'SPIDER_MODULES = ['dongguan.spiders']
    NEWSPIDER_MODULE = 'dongguan.spiders'# log日志文件默认保存在当前目录,下面为日志级别,当大于或等于INFO时将被保存LOG_FILE = 'dongguan.log'
    LOG_LEVEL = 'INFO'# 爬取深度设置# DEPTH_LIMIT = 1# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = 'dongguan (+http://www.yourdomain.com)'# Obey robots.txt rules# ROBOTSTXT_OBEY = True# Configure maximum concurrent requests performed by Scrapy (default: 16)#CONCURRENT_REQUESTS = 32# Configure item pipelines# See https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlITEM_PIPELINES = {'dongguan.pipelines.DongguanPipeline': 300,
    }
    
  6. 测试运行爬虫,终端执行命令(只要在项目目录内即可)

    scrapy crawl dg
    

Spider版流程如下:

  1. 创建爬虫项目newdongguang

    scrapy startproject newdongguan
    
  2. 设置items.py文件

    
    # -*- coding: utf-8 -*-import scrapyclass NewdongguanItem(scrapy.Item):# 每页的帖子链接url = scrapy.Field()# 帖子标题title = scrapy.Field()# 帖子编号number = scrapy.Field()# 帖子内容content = scrapy.Field()
  3. 在spiders目录里面,创建并编写爬虫文件newsun.py

    
    # -*- coding: utf-8 -*-import scrapy
    from newdongguan.items import NewdongguanItemclass NewsunSpider(scrapy.Spider):name = 'ndg'# 设置爬取的域名范围,可写可不写,不写则表示爬取时候不限域名,结果有可能会导致爬虫失控。allowed_domains = ['wz.sun0769.com']offset = 0url = 'http://wz.sun0769.com/index.php/question/report?page=' + str(offset)start_urls = [url]def parse(self, response):link_list = response.xpath("//a[@class='news14']/@href").extract()for each in link_list:# 对每页的帖子发送请求,获取帖子内容里面指定数据返回给管道文件yield scrapy.Request(each,callback=self.deal_link)self.offset += 30if self.offset <= 124260:url = 'http://wz.sun0769.com/index.php/question/report?page=' + str(self.offset)# 对指定分页发送请求,响应交给parse函数处理yield scrapy.Request(url,callback=self.parse)# 从每个分页帖子内容获取数据,返回给管道def deal_link(self,response):item = NewdongguanItem()item['url'] = response.urlitem['title'] = response.xpath("//div[@class='pagecenter p3']//strong[@class='tgray14']/text()").extract()[0]item['number'] = response.xpath("//div[@class='pagecenter p3']//strong[@class='tgray14']/text()").extract()[0].split(' ')[-1].split(':')[-1]if len(response.xpath("//div[@class='contentext']")) == 0:item['content'] = ''.join(response.xpath("//div[@class='c1 text14_2']/text()").extract())else:item['content'] = ''.join(response.xpath("//div[@class='contentext']/text()").extract())yield item
    
  4. 编写管道pipelines.py文件

    
    # -*- coding: utf-8 -*-import codecs
    import jsonclass NewdongguanPipeline(object):def __init__(self):# 使用codecs写文件,直接设置文件内容编码格式,省去每次都要对内容进行编码self.file = codecs.open('newdongguan.json','w',encoding = 'utf-8')# 以前文件写法# self.file = open('newdongguan.json','w')def process_item(self, item, spider):print(item['title'])content = json.dumps(dict(item),ensure_ascii=False) + '\n'# 以前文件写法# self.file.write(content.encode('utf-8'))self.file.write(content)return itemdef close_spider(self):self.file.close()
    
  5. 编写settings.py文件

    
    # -*- coding: utf-8 -*-BOT_NAME = 'newdongguan'SPIDER_MODULES = ['newdongguan.spiders']
    NEWSPIDER_MODULE = 'newdongguan.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = 'newdongguan (+http://www.yourdomain.com)'USER_AGENT = 'User-Agent:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;'# Configure item pipelines# See https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlITEM_PIPELINES = {'newdongguan.pipelines.NewdongguanPipeline': 300,
    }
    
  6. 测试运行爬虫,终端执行命

    srapy crawl ndg
    

备注:markdown语法关于代码块缩进问题,可通过tab键来解决。而简单文本则可以通过回车键来解决,如Spider版流程如下:和1. 创建爬虫项目newdongguang

使用scrapy爬取阳光热线问政平台相关推荐

  1. 爬虫Scrapy框架学习(五)-东莞阳光热线问政平台爬取案例

    本案例通过典型的scrapy框架Spider类展现了一个模板式的爬虫过程,请读者细细体会,此案例为必会项目,按照本博客配置,完美通过.本文还对item做了限制,编写item文件的主要作用是防止爬取数据 ...

  2. scrapy爬取阳光电影网全站资源

    说一下我的爬取过程吧 第一步: 当然是 scrapy startproject  + 名字   新建爬虫项目 第二步:  scrapy genspider -t crawl +爬虫名字+ 所爬取网站的 ...

  3. Python:阳光热线问政平台爬虫

    爬取投诉帖子的编号.帖子的url.帖子的标题,和帖子里的内容. items.py import scrapyclass DongguanItem(scrapy.Item):# 每个帖子的标题title ...

  4. python爬虫——用Scrapy框架爬取阳光电影的所有电影

    python爬虫--用Scrapy框架爬取阳光电影的所有电影 1.附上效果图 2.阳光电影网址http://www.ygdy8.net/index.html 3.先写好开始的网址 name = 'yg ...

  5. scrapy 解析css,Scrapy基础(六)————Scrapy爬取伯乐在线一通过css和xpath解析文章字段...

    上次我们介绍了scrapy的安装和加入debug的main文件,这次重要介绍创建的爬虫的基本爬取有用信息 通过命令(这篇博文)创建了jobbole这个爬虫,并且生成了jobbole.py这个文件,又写 ...

  6. 基于Python、scrapy爬取软考在线题库

    前言 前段时间,报名个软件设计师考试,自然需要复习嘛,看到软考在线这个平台有历年来的题目以及答案,想法就是做一个题库小程序咯,随时随地可以打开复习.很多人问,这不出现很多类似的小程序了?是的,但是他们 ...

  7. 用Scrapy爬取分析了7万款App,结果万万没想到!

    作者 | 苏克 来源 | 第2大脑 这是新年的第一篇原创干货. 摘要:使用 Scrapy 爬取豌豆荚全网 70,000+ App,并进行探索性分析. 写在前面:若对数据抓取部分不感兴趣,可以直接下拉到 ...

  8. 以豌豆荚为例,用 Scrapy 爬取分类多级页面

    本文转载自以下网站:以豌豆荚为例,用 Scrapy 爬取分类多级页面 https://www.makcyun.top/web_scraping_withpython17.html 需要学习的地方: 1 ...

  9. scrapy爬取海贼王漫画

    scrapy爬取海贼王漫画 1.创建项目scrapy startproject onepiecesScrapy 2.创建spider cd onepieces Scrapy scrapy genspi ...

  10. Scrapy 爬取 分析了 7 万款 App,全是没想到

    摘要:使用 Scrapy 爬取豌豆荚全网 70,000+ App,并进行探索性分析. 写在前面:若对数据抓取部分不感兴趣,可以直接下拉到数据分析部分. 1 分析背景 之前我们使用了 Scrapy 爬取 ...

最新文章

  1. UIPickerView 修改必须滚动才修改值的bug
  2. java web 里的JSP 对象的简单了解
  3. css之其它技巧和经验列表
  4. webRTC——浏览器里的音视频通话
  5. 【深度学习图像项目实战-从入门到上线1】怎样学会科学的调研并启动一个项目...
  6. AAAI 2021 | 幻灯片中文字的重要性预测赛亚军DeepBlueAI团队技术分享
  7. 【数据结构与算法】【算法思想】【算法应用】【排序查找搜索】并行
  8. SpringBoot—jasypt加解密库的使用方法
  9. golang mysql单例模式_Golang设计模式——单例模式
  10. 图像空域增强:灰度映射法
  11. Python基础10—I/O编程
  12. 用友U8 ERP系统材料出库单打印格式设置-表格格式调整
  13. 传智播客python培训视频教程下载
  14. Redis报错:WRONGTYPE Operation against a key holding the wrong kind of value
  15. hexo笔记十五:next主题添加网易云外链
  16. 海尔希望小学:同一片蓝天下梦想启航
  17. 3D点云深度学习综述
  18. 移动金融客户端应用软件备案、中国支付清算协会“聚合支付”业务备案、工业和信息化部网站备案系统(ICP备案)
  19. 基于FPGA数字混频器的设计(1)
  20. 写一段潮汐调和分析的matlab代码

热门文章

  1. 决策树分析例题经典案例_决策树分类的实例
  2. 漫话中文分词和语义识别(下):句法结构和语义结构
  3. OSChina 周一乱弹 ——生活不止眼前的苟且
  4. ALV 单元格控制参数LVC_S_STYL排序问题
  5. html如何书页样式,CSS案例:实现书页任意折角效果
  6. VTN泛读【Video Transformer Network】
  7. nginx配置ssl证书
  8. Python chain函数的用法
  9. SIP软电话开发的基本条件和要点
  10. jquery实现登录成功界面_【jQuery实例】Ajax登录页面