• 爬取投诉帖子的编号、帖子的url、帖子的标题,和帖子里的内容。地址:http://wz.sun0769.com/index.php/question/questionType?type=4

  • 使用Scrapy命令生成项目工程和爬虫类:

scrapy startproject dongguan

scrapy genspider sun "wz.sun0769.com"

编码步骤

1.items.py

import scrapyclass DongguanItem(scrapy.Item):# 每个帖子的标题title = scrapy.Field()# 每个帖子的编号number = scrapy.Field()# 每个帖子的文字内容content = scrapy.Field()# 每个帖子的urlurl = scrapy.Field()

2.spiders/sunwz.py

Spider 版本

# -*- coding: utf-8 -*-import scrapy
from dongguan.items import DongguanItemclass SunSpider(CrawlSpider):name = 'sun'allowed_domains = ['wz.sun0769.com']url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page='offset = 0start_urls = [url + str(offset)]def parse(self, response):# 取出每个页面里帖子链接列表links = response.xpath("//div[@class='greyframe']/table//td/a[@class='news14']/@href").extract()# 迭代发送每个帖子的请求,调用parse_item方法处理for link in links:yield scrapy.Request(link, callback = self.parse_item)# 设置页码终止条件,并且每次发送新的页面请求调用parse方法处理if self.offset <= 71130:self.offset += 30yield scrapy.Request(self.url + str(self.offset), callback = self.parse)# 处理每个帖子里def parse_item(self, response):item = DongguanItem()# 标题item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]# 编号item['number'] = item['title'].split(' ')[-1].split(":")[-1]# 文字内容,默认先取出有图片情况下的文字内容列表content = response.xpath('//div[@class="contentext"]/text()').extract()# 如果没有内容,则取出没有图片情况下的文字内容列表if len(content) == 0:content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()# content为列表,通过join方法拼接为字符串,并去除首尾空格item['content'] = "".join(content).strip()else:item['content'] = "".join(content).strip()# 链接item['url'] = response.urlyield item

CrawlSpider 版本


# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from dongguan.items import DongguanItem
import timeclass SunSpider(CrawlSpider):name = 'sun'allowed_domains = ['wz.sun0769.com']start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']# 每一页的匹配规则pagelink = LinkExtractor(allow=('type=4'))# 每个帖子的匹配规则contentlink = LinkExtractor(allow=r'/html/question/\d+/\d+.shtml')rules = [# 本案例为特殊情况,需要调用deal_links方法处理每个页面里的链接Rule(pagelink, process_links = "deal_links", follow = True),Rule(contentlink, callback = 'parse_item')]# 需要重新处理每个页面里的链接,将链接里的‘Type&type=4?page=xxx’替换为‘Type?type=4&page=xxx’(或者是Type&page=xxx?type=4’替换为‘Type?page=xxx&type=4’),否则无法发送这个链接def deal_links(self, links):for link in links:link.url = link.url.replace("?","&").replace("Type&", "Type?")print link.urlreturn linksdef parse_item(self, response):print response.urlitem = DongguanItem()# 标题item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]# 编号item['number'] = item['title'].split(' ')[-1].split(":")[-1]# 文字内容,默认先取出有图片情况下的文字内容列表content = response.xpath('//div[@class="contentext"]/text()').extract()# 如果没有内容,则取出没有图片情况下的文字内容列表if len(content) == 0:content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()# content为列表,通过join方法拼接为字符串,并去除首尾空格item['content'] = "".join(content).strip()else:item['content'] = "".join(content).strip()# 链接item['url'] = response.urlyield item

3.pipelines.py

# -*- coding: utf-8 -*-# 文件处理类库,可以指定编码格式
import codecs
import jsonclass JsonWriterPipeline(object):def __init__(self):# 创建一个只写文件,指定文本编码格式为utf-8self.filename = codecs.open('sunwz.json', 'w', encoding='utf-8')def process_item(self, item, spider):content = json.dumps(dict(item), ensure_ascii=False) + "\n"self.filename.write(content)return itemdef spider_closed(self, spider):self.file.close()

4.settings.py

ITEM_PIPELINES = {'dongguan.pipelines.DongguanPipeline': 300,
}# 日志文件名和处理等级
LOG_FILE = "dg.log"
LOG_LEVEL = "DEBUG"

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

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

5.执行程序

py2 main.py

Scrapy实战之阳光热线问政平台相关推荐

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

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

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

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

  3. 爬虫教程( 2 ) --- 爬虫框架 Scrapy、Scrapy 实战

    From:https://piaosanlang.gitbooks.io/spiders/content/ scrapy-cookbook :https://scrapy-cookbook.readt ...

  4. 爬虫笔记八——Scrapy实战项目

    (案例一)手机App抓包爬虫 1. items.py import scrapyclass DouyuspiderItem(scrapy.Item):# 存储照片的名字 nickName = scra ...

  5. python爬取新浪微博数据中心_Python爬虫框架Scrapy实战之批量抓取招聘信息

    网络爬虫抓取特定网站网页的html数据,但是一个网站有上千上万条数据,我们不可能知道网站网页的url地址,所以,要有个技巧去抓取网站的所有html页面.Scrapy是纯Python实现的爬虫框架,用户 ...

  6. Python 网络爬虫笔记11 -- Scrapy 实战

    Python 网络爬虫笔记11 – Scrapy 实战 Python 网络爬虫系列笔记是笔者在学习嵩天老师的<Python网络爬虫与信息提取>课程及笔者实践网络爬虫的笔记. 课程链接:Py ...

  7. spark项目实战:电商分析平台之各个范围Session步长、访问时长占比统计(需求一)

    spark项目实战:电商分析平台之各个范围Session步长.访问时长占比统计(需求一) 项目基本信息,架构,需要一览 各个范围Session步长.访问时长占比统计概述 各个范围Session步长.访 ...

  8. spark项目实战:电商分析平台之项目概述

    spark项目实战:电商分析平台之项目概述 目录 项目概述 程序架构分析 需求解析 初始代码和完成代码存放在github上面 1. 项目概述 在访问电商网站时,我们的一些访问行为会产生相应的埋点日志( ...

  9. swift语言实战晋级-第9章 游戏实战-跑酷熊猫-7-8 移动平台的算法

    原文:swift语言实战晋级-第9章 游戏实战-跑酷熊猫-7-8 移动平台的算法 在上个小节,我们完成了平台的产生.那么我们来实现一下让平台移动.平台的移动,我们只需要在平台工厂类中写好移动的方法,然 ...

  10. Swift游戏实战-跑酷熊猫 12 与平台的碰撞

    原文:Swift游戏实战-跑酷熊猫 12 与平台的碰撞 这节主要实现熊猫和平台的碰撞,实现熊猫在平台上奔跑 要点 对平台进行物理属性设置 //设置物理体以及中心点 self.physicsBody = ...

最新文章

  1. oracle 无备份恢复数据文件
  2. php 计算一个字符串在另一个字符串中出现的次数
  3. Cloud Service Process Pack
  4. python专科找工作难吗-本人小白,想学python,大专不知道好不好找工作?
  5. SQL Tips:兼顾检索速度和精确性
  6. Quartz 框架快速入门(四)
  7. mybatis学习(26):插入功能(插入数据)
  8. [转载] python __slots__ 详解(上篇)
  9. python 发送邮件connect none_使用python向IP地址发送邮件
  10. 1 MLP-Mixer: An all-MLP Architecture for Vision
  11. 软件先行的英特尔,为开发者们带来了什么?
  12. 【500-Lines-or-Less】-【翻译练习】-【chapter-14】-【简单对象模型】-【第三部分】...
  13. 阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第2节 线程实现方式_10_Thread类的常用方法_设置线程名称...
  14. arcgis批量裁剪tif文件
  15. C#姓名与机构名称生成专用类
  16. Windows下查看进程及结束进程命令
  17. HTML期末作业-我的大学宿舍
  18. 自动化测试的优缺点分析
  19. jacob实现ppt转图片时存在的问题
  20. ctfshow七夕杯 writeup

热门文章

  1. python—wordcloud库绘制词云
  2. c++ de-mangle 反编译器命名工具:c++filt
  3. python学习第二天——编写名片
  4. deepin系统引导_Deepin系统安装教程
  5. Unity - 射线检测
  6. 性早熟和微生物群:性激素-肠道菌群轴的作用
  7. 图片降噪Topaz DeNoise AI 安装小技巧
  8. android访问服务器405,android
  9. m3u8解析php,PHP解码转发M3U8 PHP读取转发M3U8的方法
  10. 华为荣耀9刷Android9.0,华为荣耀手机,安卓9.0/EMUI9.0升级常见问题大汇总!