Python使用scrapy爬取阳光热线问政平台过程解析


Posted in Python onAugust 14, 2019

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

CrawlSpider版流程如下:

创建爬虫项目dongguang

scrapy startproject dongguang

设置items.py文件

# -*- coding: utf-8 -*-
import scrapy
class NewdongguanItem(scrapy.Item):
  # define the fields for your item here like:
  # name = scrapy.Field()
  # pass
  # 每页的帖子链接
  url = scrapy.Field()
  # 帖子标题
  title = scrapy.Field()
  # 帖子编号
  number = scrapy.Field()
  # 帖子内容
  content = scrapy.Field()

在spiders目录里面,创建并编写爬虫文件sun.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from dongguan.items import DongguanItem
class 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后返回一个真的url
  rules = (
    # 每个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.url
    item['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]
     # 对帖子里面有图片的处理,发现没有图片时则没有class="contentext"的div标签,以此作为标准获取帖子内容
    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

编写管道pipelines.py文件

# -*- coding: utf-8 -*-
import json
class 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 item
  def closespider(self):
    self.file.close()

编写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.html
ITEM_PIPELINES = {
  'dongguan.pipelines.DongguanPipeline': 300,
}

测试运行爬虫,终端执行命令(只要在项目目录内即可)

scrapy crawl dg

Spider版流程如下:

创建爬虫项目newdongguang

scrapy startproject newdongguan

设置items.py文件

# -*- coding: utf-8 -*-
  import scrapy
  class NewdongguanItem(scrapy.Item):
    # 每页的帖子链接
    url = scrapy.Field()
    # 帖子标题
    title = scrapy.Field()
    # 帖子编号
    number = scrapy.Field()
    # 帖子内容
    content = scrapy.Field()

在spiders目录里面,创建并编写爬虫文件newsun.py

# -*- coding: utf-8 -*-
import scrapy
from newdongguan.items import NewdongguanItem
class NewsunSpider(scrapy.Spider):
  name = 'ndg'
  # 设置爬取的域名范围,可写可不写,不写则表示爬取时候不限域名,结果有可能会导致爬虫失控。
  allowed_domains = ['wz.sun0769.com']
  offset = 0
  url = '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 += 30
    if 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.url
    item['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

编写管道pipelines.py文件

# -*- coding: utf-8 -*-
import codecs
import json
class 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 item

  def close_spider(self):
    self.file.close()

编写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.html
ITEM_PIPELINES = {
  'newdongguan.pipelines.NewdongguanPipeline': 300,
}

测试运行爬虫,终端执行命

srapy crawl ndg

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
深入解析Python编程中JSON模块的使用
Oct 15 Python
Python基于QRCode实现生成二维码的方法【下载,安装,调用等】
Jul 11 Python
浅析使用Python操作文件
Jul 31 Python
Python使用matplotlib绘制多个图形单独显示的方法示例
Mar 14 Python
Flask框架WTForm表单用法示例
Jul 20 Python
OpenCV+python手势识别框架和实例讲解
Aug 03 Python
python+tifffile之tiff文件读写方式
Jan 13 Python
基于TensorBoard中graph模块图结构分析
Feb 15 Python
Python打包工具PyInstaller的安装与pycharm配置支持PyInstaller详细方法
Feb 27 Python
Python requests及aiohttp速度对比代码实例
Jul 16 Python
Python list和str互转的实现示例
Nov 16 Python
使用pandas生成/读取csv文件的方法实例
Jul 09 Python
用Python抢火车票的简单小程序实现解析
Aug 14 #Python
Python定时任务随机时间执行的实现方法
Aug 14 #Python
查看Python依赖包及其版本号信息的方法
Aug 13 #Python
使用python实现unix2dos和dos2unix命令的例子
Aug 13 #Python
Python编写带选项的命令行程序方法
Aug 13 #Python
使用python模拟命令行终端的示例
Aug 13 #Python
在macOS上搭建python环境的实现方法
Aug 13 #Python
You might like
PHP实现文件安全下载
2006/10/09 PHP
PHP中$_SERVER的详细参数与说明
2008/07/29 PHP
PHP中冒号、endif、endwhile、endfor使用介绍
2010/04/28 PHP
浅谈PHP强制类型转换,慎用!
2013/06/06 PHP
具有时效性的php加密解密函数代码
2013/06/19 PHP
PHP操作MySQL事务实例
2014/11/05 PHP
php使用curl获取header检测开启GZip压缩的方法
2018/08/15 PHP
Javascript this关键字使用分析
2008/10/21 Javascript
在JavaScript中操作时间之getYear()方法的使用教程
2015/06/11 Javascript
原生JS实现几个常用DOM操作API实例
2017/01/19 Javascript
js获取隐藏元素的宽高
2017/02/24 Javascript
jQuery EasyUI Panel面板组件使用详解
2017/02/28 Javascript
div中文字内容溢出常见的解决方法
2017/03/16 Javascript
Vue 莹石摄像头直播视频实例代码
2018/08/31 Javascript
Vue.js更改调试地址端口号的实例
2018/09/19 Javascript
Node.js 多线程完全指南总结
2019/03/27 Javascript
对node通过fs模块判断文件是否是文件夹的实例讲解
2019/06/10 Javascript
python中使用sys模板和logging模块获取行号和函数名的方法
2014/04/15 Python
Python文件右键找不到IDLE打开项解决办法
2015/06/08 Python
Python实现统计代码行的方法分析
2017/07/12 Python
Python for循环与range函数的使用详解
2019/03/23 Python
使用python制作一个解压缩软件
2019/11/13 Python
Python中的X[:,0]、X[:,1]、X[:,:,0]、X[:,:,1]、X[:,m:n]和X[:,:,m:n]
2020/02/13 Python
Django实现后台上传并显示图片功能
2020/05/29 Python
python 实现Harris角点检测算法
2020/12/11 Python
美国一站式电动和手动工具商店:International Tool
2020/11/26 全球购物
介绍一下Python中webbrowser的用法
2013/05/07 面试题
活动策划邀请函
2014/02/06 职场文书
幼儿园元旦家长感言
2014/02/27 职场文书
我们的节日端午节活动方案
2014/03/02 职场文书
黄金酒广告词
2014/03/21 职场文书
荷叶母亲教学反思
2014/04/30 职场文书
村班子对照检查材料
2014/08/18 职场文书
个人对照检查材料思想汇报
2014/09/26 职场文书
幼师大班个人总结
2015/02/13 职场文书
2016年社区六一儿童节活动总结
2016/04/06 职场文书