阳光热线问政平台

http://wz.sun0769.com/index.php/question/questionType?type=4

爬取投诉帖子的编号、帖子的url、帖子的标题,和帖子里的内容。

items.py

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

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
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()
settings.pyITEM_PIPELINES = {'dongguan.pipelines.DongguanPipeline': 300,
}# 日志文件名和处理等级
LOG_FILE = "dg.log"
LOG_LEVEL = "DEBUG"

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

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

执行程序

py2 main.py

(实战项目二)阳光热线问政平台相关推荐

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

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

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

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

  3. 【机器学习】KNN算法实战项目二:水果分类

    KNN算法实战项目二:水果分类 2 KNN实现水果分类 2.1 模块导入与数据加载 2.2 数据EDA 2.3 模型创建与应用 2.4 绘制决策边界 手动反爬虫: 原博地址 https://blog. ...

  4. 分布式爬虫联系项目1–阳光热线网站的分布式爬取

    要爬取的目标网站地址:http://wz.sun0769.com/political/index/politicsNewest?id=1&page=1 要爬取的内容为问政标题和处理状态. 1. ...

  5. Halcon实战 项目二 Bolb实战分析-提取图片中的硬币

    ○读取图像 Halcon读取图像有三种方式:a文件->读取图像:b通过助手(连接相机,声称读取图像代码):c代码输入. 本案例使用链接相机读取图像. ○链接相机-生成代码选择采集gray灰度图像 ...

  6. 数据分析项目实战项目二:入驻商用户画像体系

    第一章:电商平台入驻商数据分析思路与亚马逊相关信息介绍 1.1 互联网电商平台入驻商数据分析的一般思路 互联网电商平台入驻商数据分析的一般思路一般分为以下三步:获得数据,分析业务需求,产生数据成果.其 ...

  7. Java实战项目二(超详细)---奔跑吧小恐龙

    奔跑吧小恐龙是一款简单的跑酷游戏(代码简单,适合初学者学习).玩家控制小恐龙向前狂奔,躲避沿途出现的石头和仙人掌,跑的越远,分数越高.游戏内还增加了背景音乐.跳跃音乐和碰撞音乐. 本文的代码虽然长,但 ...

  8. 【大数据实战项目二】Spark环境和Mongo、ES数据库安装,以及数据库与Spark,Python联动

    Spark和Mongodb软件安装与python交互测试 3.1 python处理文件 3.2 搭建Spark开发环境和测试 3.3 搭建Mongodb和ES数据库及测试 3.3.1 Mongodb安 ...

  9. 实战项目二:实现CSDN自动点赞

    环境: Python3.6.5 编译器: Sublime Text 3 代码: GitHub 联系方式: ke.zb@qq.com 第三方库: selenium 写在前面:本文仅供参考学习,请勿用作它 ...

  10. 02- 天池工业蒸汽量项目实战 (项目二) *

    忽略警告: warnings.filterwarnings("ignore") import warnings warnings.filterwarnings("igno ...

最新文章

  1. 圆角阴影_Win10新界面曝光,圆角设计加阴影半透明,更招年轻人喜欢
  2. 用Microsoft Application Center Test测试Web应用程序性能
  3. COJ1005(Binary Search Tree analog)
  4. 公网传输技术之SRT协议解析(上)
  5. 今日头条Web HTTP请求的白名单
  6. Qtcreator中经常使用快捷键总结
  7. AI智能内容创作的几个方面
  8. 用TCP/IP实现自己简单的应用程序协议:成帧器部分
  9. C++ 中两个数据交换总结
  10. Steam的Hacknet的账户损坏问题
  11. Python修改图片格式
  12. 2021年广东专精特新中小企业补助及小巨人企业补贴
  13. MYSQL安装遇到MySQL-server conflicts with错误(mysql5.6.17)
  14. Attack State Slight Movement(攻击状态)
  15. ARM(ARM处理器) x64和x86
  16. iOS获取屏幕尺寸的方法
  17. Unity获取系统信息SystemInfo(CPU、显卡、操作系统等信息)
  18. DelphiXE Update1
  19. 使用ant直接执行shell命令
  20. 每日算法(四十三)-java为了更改的规划城市,需要统计楼栋数目信息。

热门文章

  1. xp系统怎么关闭wmi服务器,教你win10系统wmi服务器怎么关闭
  2. 资产管理系统——必备功能
  3. 大麦DW33D路由器假死
  4. 清华大学出来的工资有多高?| 文末送书
  5. vue运行之神奇的npm install --legacy-peer-deps
  6. android 实现层叠列表,RecyclerView进阶之层叠列表(下)
  7. 巴黎世家土味病毒营销,B端创业初期,如何用营销壮大你的种子用户?
  8. python制作日历并保存成excel_[python]获取一年日历数据并写入excel表格中
  9. H5与SCC3的新特性
  10. 代码统计工具 cloc 和 scc