首页 > 其他分享 >一、 采集北京市政百姓信件内容

一、 采集北京市政百姓信件内容

时间:2023-05-26 22:22:07浏览次数:47  
标签:string self replace 采集 scrapy processed 信件 市政 type

letter.py

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from letterBeijing.items import LetterbeijingItem
import json

i = 1

class LetterSpider(scrapy.Spider):
    name = "letter"
    allowed_domains = ["www.beijing.gov.cn"]
    start_urls = ["https://www.beijing.gov.cn/hudong/hdjl/sindex/bjah-index-hdjl!letterListJson.action?keyword=&startDate=&endDate=&letterType=0&page.pageNo=1&page.pageSize=6&orgtitleLength=26"]

    def parse(self, response):
        input_string = response.text
        # 处理字符串,使用双引号替换键名和字符串值的单引号
        processed_string = input_string.replace("'", "\"")
        processed_string = processed_string.replace("page:", "\"page\":")
        processed_string = processed_string.replace("pageNo:", "\"pageNo\":")
        processed_string = processed_string.replace("totalCount:", "\"totalCount\":")
        processed_string = processed_string.replace("totalPages:", "\"totalPages\":")
        processed_string = processed_string.replace("pageSize:", "\"pageSize\":")
        processed_string = processed_string.replace("result:", "\"result\":")
        processed_string = processed_string.replace("letterType:", "\"letterType\":")
        processed_string = processed_string.replace("letterTypeName:", "\"letterTypeName\":")
        processed_string = processed_string.replace("letterTitle:", "\"letterTitle\":")
        processed_string = processed_string.replace("showLetterTitle:", "\"showLetterTitle\":")
        processed_string = processed_string.replace("writeDate:", "\"writeDate\":")
        processed_string = processed_string.replace("orgNames:", "\"orgNames\":")
        processed_string = processed_string.replace("showOrgNames:", "\"showOrgNames\":")
        processed_string = processed_string.replace("originalId:", "\"originalId\":")

        contents = json.loads(processed_string)["result"]

        for content in contents:
            # 详情内容的url
            url = ["https://www.beijing.gov.cn/hudong/hdjl/com.web.consult.consultDetail.flow?originalId=",
                   "https://www.beijing.gov.cn/hudong/hdjl/com.web.suggest.suggesDetail.flow?originalId=",
                   ]
            # 内容类型
            type = content["letterTypeName"]
            # 内容标题
            title = content["letterTitle"]
            # 处理机构
            institution = content["showOrgNames"]

            if(type=="咨询"):
                yield scrapy.Request(url=url[0]+content["originalId"],callback=self.parse_second,meta={'type':type,'title':title,'institution':institution})
            elif(type=="建议"):
                yield scrapy.Request(url=url[1]+content["originalId"],callback=self.parse_second,meta={'type':type,'title':title,'institution':institution})


    def parse_second(self,response):
        # 信件内容
        content = response.xpath('//div[@class="col-xs-12 col-md-12 column p-2 text-muted mx-2"]/text()').extract_first()
        # 回复内容
        reply = response.xpath('//div[@class="col-xs-12 col-md-12 column p-4 text-muted my-3"]/text()').extract_first()
        type = response.meta['type']
        title = response.meta['title']
        institution = response.meta['institution']

        letter = LetterbeijingItem(type=type,title=title,content=content,institution=institution,reply=reply)

        yield letter
        global i
        i += 1
        url = "https://www.beijing.gov.cn/hudong/hdjl/sindex/bjah-index-hdjl!letterListJson.action?keyword=&startDate=&endDate=&letterType=0&page.pageNo="+str(i)+"&page.pageSize=6&orgtitleLength=26";
        if(i<150):
            yield scrapy.Request(url=url,callback=self.parse,dont_filter = False)

items.py

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

import scrapy


class LetterbeijingItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    # 信件类型
    type = scrapy.Field()
    # 信件标题
    title = scrapy.Field()
    # 信件内容
    content = scrapy.Field()
    # 处理部门
    institution = scrapy.Field()
    # 答复内容
    reply = scrapy.Field()

pipelines.py

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


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exporters import JsonLinesItemExporter

class LetterbeijingPipeline:
    def __init__(self):
        self.file = open('letter.json', 'wb')  # 必须写入二进制
        self.exporter = JsonLinesItemExporter(self.file, ensure_ascii=False, encoding='utf-8')

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        print(item)

    def close_item(self, spider):
        self.file.close()

letter.json

https://github.com/HE-ZI-YAN/letterBeijing/blob/main/letterBeijing/letter.json

标签:string,self,replace,采集,scrapy,processed,信件,市政,type
From: https://www.cnblogs.com/java-six/p/17435960.html

相关文章

  • 仓库温湿度物联网采集方案
    一、项目介绍U型地下仓库,采集点30个,每个采集点采集温度湿度,最远约100米,常温20~30度。需要物联网采集系统将温湿度上传至第三方系统数据库。二、解决方案方案一:系统拓扑图U型地下仓库,每个采集点的温度湿度传感器,通过RS485总线并联接到WG585MQTT网关的串口上。由于地下室的信号很弱,......
  • 远距离数据采集,来一个远程 IO模块搞定!
    远程IO模块主要用于工业现场采集模拟信号和数字信号,而且还可以输出模拟信号和数字信号来控制设备。可以扩展PLC、采集仪器仪表等数据处理设备的输入和输出口,比如一个PLC只有有10个模拟输入接口,但是现场需要采集30个模拟量,就需要加入远程IO扩展。还有,由于设备和主控PLC或工控机可能......
  • 度衍专利采集一版
    importhashlibimportrandomimporttimefromurllib.parseimportquote,unquoteimportpymysqlimportrequestsfromlxmlimportetree#把唯一值进行MD5加密defget_md5(parmStr):#1、参数必须是utf8#2、python3所有字符都是unicode形式,已经不存在unicode关键字......
  • 多功能RTU环境采集网关支持温湿度风速采集
    无线工业物联网数据采集控制短信报警终端S475/S475E系列在工业物联网产业链中发挥着非常重要的作用,可以广泛应用于很多领域,例如智能电网、智能交通、智能家居、金融、移动POS终端、供应链自动化、工业自动化等。该系列产品内嵌工业级GSM/GPRS/3G/4G通信模块,并集成了稳定可靠......
  • 分享Python采集77个焦点图,总有一款适合您
    Python采集的77个焦点图下载链接:https://pan.baidu.com/s/1DwOhWYWWRYHnAy-ZwWBTmg?pwd=xj5a提取码:xj5ajQuery全屏背景跟随手风琴图片切换特效HTML5焦点图片波浪过渡效果切换动画特效jQuery+HTML53D折页图片切换特效jQuery图片手风琴滑动展开特效jQuery点击右侧按钮图片滑动切换......
  • 集成 GPRS/3G/4G 通信模块,可实现远程数据采集和监测
    随着物联网技术的不断发展,各行各业都在积极探索物联网技术在自身领域的应用。而工业物联网作为其中的一个重要分支,更是应用广泛、前景广阔。S475/S475E系列多功能可编程无线工业物联网数据监测采集控制短信报警终端,正是在这样的大背景下应运而生的。本文将从应用场景、产品特点等方......
  • 电商erp系统选品,跨境ERP系统选品,api接口采集数据
    ​  电商ERP系统选品优势:1.自动化选品:电商ERP系统可以根据销售数据、客户反馈、市场趋势等因素,自动化地筛选出热销商品,快速进行选品;2.数据分析功能:电商ERP系统可以对历史销售数据进行分析,得出销售趋势、客户偏好等信息,有利于精细化选品;3.库存管理:电商ERP系统可以管理商......
  • 烟雨黑帽程序定制开发反向代理泛目录站群程序-自动相关词+自动采集+文章拼音繁体伪原
     我是烟雨QQ81047380,演示下客户最新定制程序,本套泛目录站群程序适用于反向代理租目录时使用,也可以使用域名做目录站群。 泛目录站群程序功能介绍:1.自动相关词,比如页面关键词是”淡水龙虾养殖“,会自动匹配相关关键词:淡水龙虾养殖技术,淡水龙虾养殖周期多久,澳洲淡水龙虾养......
  • 以太网IO模块:高精度数据采集和快速传输
    随着工业自动化的不断发展和普及,以太网IO模块被广泛应用于控制和监测系统中。该模块具有高精度数据采集和快速传输等特点,使其成为工业自动化应用中不可或缺的重要器件。深圳市钡铼技术有限公司是一家高新技术企业,【钡铼】与【BLIIOT】都是公司品牌,专注工业物联网关、工业智能网关、......
  • 【云原生•监控】Categraf大一统的监控数据采集器​
    【云原生•监控】Categraf大一统的监控数据采集器前言「笔者已经在公有云上搭建了一套临时环境,可以先登录体验下:」http://124.222.45.207:17000/login账号:root/root.2020简介Categraf是一个监控采集Agent,类似Telegraf、Grafana-Agent、Datadog-Agent,希望对所有常见监控对象提供......