爬虫——Scrapy框架案例二:阳光问政平台

阳光热线问政平台

URL地址:http://wz.sun0769.com/index.php/question/questionType?type=4&page=

爬取字段:帖子的编号、投诉类型、帖子的标题、帖子的URL地址、部门、状态、网友、时间。

1.items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class SunwzspiderItem(scrapy.Item):
    # define the fields for your item here like:
    # 爬取投诉帖子的编号、投诉类型、帖子的标题、帖子的URL、部门、状态、网友、时间。
    # 帖子的编号
    post_id = scrapy.Field()
    # 投诉类型
    post_type = scrapy.Field()
    # 帖子的标题
    post_title = scrapy.Field()
    # 帖子的URL
    post_url = scrapy.Field()
    # 部门
    sector = scrapy.Field()
    # 状态
    post_state = scrapy.Field()
    # 网友
    net_friend = scrapy.Field()
    # 时间
    post_time = scrapy.Field()

2.spiders/sunwz.py

# -*- coding: utf-8 -*-
import scrapy
from sunwzSpider.items import SunwzspiderItem

class SunwzSpider(scrapy.Spider):
    name = ‘sunwz‘
    allowed_domains = [‘wz.sun0769.com‘]
        url = "http://wz.sun0769.com/index.php/question/questionType?type=4&page="
    offset = 0
    start_urls = [url + str(offset)]

    def parse(self, response):
        table = response.xpath("//table[@width=‘98%‘]")[0]
        trs = table.xpath("./tr")
        # 是否爬取下一页的标记
        next_flag = False
        for tr in trs:
            next_flag = True
            try:
                item = SunwzspiderItem()
                # 帖子的编号
                post_id = tr.xpath("./td/text()").extract()[0]
                td2 = tr.xpath("./td")[1]
                # 投诉类型
                post_type = td2.xpath("./a/text()").extract()[0]
                # 帖子的标题
                post_title = td2.xpath("./a/text()").extract()[1]
                # 帖子的URL
                post_url = td2.xpath("./a/@href").extract()[1]
                # 部门
                sector = td2.xpath("./a/text()").extract()[2]
                td3 = tr.xpath("./td")[2]
                # 状态
                post_state = td3.xpath("./span/text()").extract()[0]
                # 网友
                net_friend = tr.xpath("./td/text()").extract()[3]
                # 时间
                post_time = tr.xpath("./td/text()").extract()[4]

                item["post_id"] = post_id
                item["post_type"] = post_type
                item["post_title"] = post_title
                item["post_url"] = post_url
                item["sector"] = sector
                item["post_state"] = post_state
                item["net_friend"] = net_friend
                item["post_time"] = post_time

                yield item
            except:
                pass

        # 判断是否继续爬取下一页
        if next_flag:
            self.offset += 30
            yield scrapy.Request(self.url + str(self.offset), callback = self.parse)

3.pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don‘t forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json

class SunwzspiderPipeline(object):
    def __init__(self):
        self.file = open("阳光问政平台.json", "w", encoding = "utf-8")
        self.first_flag = True

    def process_item(self, item, spider):
        if self.first_flag:
            self.first_flag = False
            content = "[\n" + json.dumps(dict(item), ensure_ascii = False)
        else:
            content = ",\n" + json.dumps(dict(item), ensure_ascii = False)
        self.file.write(content)

        return item

    def close_spider(self, spider):
        self.file.write("\n]")
        self.file.close()

4.settings.py

# -*- coding: utf-8 -*-

# Scrapy settings for sunwzSpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = ‘sunwzSpider‘

SPIDER_MODULES = [‘sunwzSpider.spiders‘]
NEWSPIDER_MODULE = ‘sunwzSpider.spiders‘

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = ‘sunwzSpider (+http://www.yourdomain.com)‘

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 2
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
   ‘Accept‘: ‘text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8‘,
   ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36‘
#   ‘Accept-Language‘: ‘en‘,
}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    ‘sunwzSpider.middlewares.SunwzspiderSpiderMiddleware‘: 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    ‘sunwzSpider.middlewares.MyCustomDownloaderMiddleware‘: 543,
#}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    ‘scrapy.extensions.telnet.TelnetConsole‘: None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    ‘sunwzSpider.pipelines.SunwzspiderPipeline‘: 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = ‘httpcache‘
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = ‘scrapy.extensions.httpcache.FilesystemCacheStorage‘
时间: 2024-11-05 21:57:34

爬虫——Scrapy框架案例二:阳光问政平台的相关文章

爬虫——Scrapy框架案例一:手机APP抓包

以爬取斗鱼直播上的信息为例: URL地址:http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset=0 爬取字段:房间ID.房间名.图片链接.存储在本地的图片路径.昵称.在线人数.城市 1.items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.s

python爬虫--scrapy框架

Scrapy 一 介绍 Scrapy简介 1.Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛 2.框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非常之方便 Scrapy架构图 Scrapy主要包括了以下组件: 1.引擎(Scrapy) 用来处理整个系统的数据流处理, 触发事务(框架核心) 2.调度器(Scheduler) 用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可

python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

操作环境:python3 在上一文中python爬虫scrapy框架--人工识别登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前的文章便于理解 本文将介绍如何用scrapy来登录知乎. 不多说,直接上代码: import scrapy import re import json class ZhihuSpider(scrapy.Spider): name = 'zhihu' allowed_domains = ['www.zhi

安装爬虫 scrapy 框架前提条件

安装爬虫 scrapy 框架前提条件 (不然 会 报错) 1 pip install pypiwin32 原文地址:https://www.cnblogs.com/xmdykf/p/11374484.html

scrapy框架(二)

scrapy框架(二) 一.scrapy 选择器 概述: Scrapy提供基于lxml库的解析机制,它们被称为选择器. 因为,它们“选择”由XPath或CSS表达式指定的HTML文档的某部分. Scarpy选择器的API非常小,且非常简单. Scrapy选择器是通过scrapy.Selector类,通过传递文本或者TextResonse对象构造的实例. 选择器Selector对象使用  选择器提供2个方法来提取标签 ? xpath()   # 基于xpath的语法规则 css() # 基于css

Python3爬虫(十八) Scrapy框架(二)

对Scrapy框架(一)的补充 Infi-chu: http://www.cnblogs.com/Infi-chu/ Scrapy优点:    提供了内置的 HTTP 缓存 ,以加速本地开发 .    提供了自动节流调节机制,而且具有遵守 robots.txt 的设置的能力.    可以定义爬行深度的限制,以避免爬虫进入死循环链接 .    会自动保留会话.    执行自动 HTTP 基本认证 . 不需要明确保存状态.    可以自动填写登录表单.    Scrapy 有一个 内置的中间件 ,

爬虫----Scrapy框架

一.介绍 Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速.简单.可扩展的方式从网站中提取所需的数据.但目前Scrapy的用途十分广泛,可用于如数据挖掘.监测和自动化测试等领域,也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫. Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架.因此Scrapy使用了一

python网络爬虫——scrapy框架持久化存储

1.基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储 scrapy crawl 爬虫名称 -o xxx.json scrapy crawl 爬虫名称 -o xxx.xml scrapy crawl 爬虫名称 -o xxx.csv 2.基于管道的持久化存储 scrapy框架中已经为我们专门集成好了高效.便捷的持

Python爬虫Scrapy框架入门(2)

本文是跟着大神博客,尝试从网站上爬一堆东西,一堆你懂得的东西 附上原创链接: http://www.cnblogs.com/qiyeboy/p/5428240.html 基本思路是,查看网页元素,填写xpath表达式,获取信息.自动爬取策略是,找到翻页网页元素,获取新链接地址,执行翻页.网页分析部分不再赘述,原博讲的很好很清楚,很涨姿势 基于拿来主义,我们只需要知道怎么更改Scrapy框架就行了~ items.py: import scrapy class TestprojItem(scrapy