31.网站数据监控-2(scrapy文件下载)

news/2024/5/20 23:01:28/文章来源:https://blog.csdn.net/weixin_34190136/article/details/94342673
31.网站数据监控-2(scrapy文件下载)
温州数据采集

这里采集网站数据是下载pdf:http://wzszjw.wenzhou.gov.cn/col/col1357901/index.html
(涉及的问题就是scrapy 文件的下载设置之前没用scrapy下载文件,所以弄了很久才弄好,网上很多不过写的都不完善。)

主要重点就是设置:
1.piplines.py  文件下载代码 这部分可以直接拿来用不需要修改。

2.就是下载文件的url要放在列表里 item['file_urls']=[url](wenzhou.py)

3. setting.py 主要配置
ITEM_PIPELINES = {
'wenzhou_web.pipelines.WenzhouWebPipeline': 300,
# 下载文件管道
'scrapy.pipelines.MyFilePipeline': 1,
}
#下载路径
FILES_STORE = './download'

4.下载的文件就会保存到download文件夹中
如图:
 
wenzhou.py

#
-*- coding: utf-8 -*- import scrapy import re from wenzhou_web.items import WenzhouWebItem class WenzhouSpider(scrapy.Spider):name = 'wenzhou'base_url=['http://wzszjw.wenzhou.gov.cn']allowed_domains = ['wzszjw.wenzhou.gov.cn']start_urls = ['http://wzszjw.wenzhou.gov.cn/col/col1357901/index.html']custom_settings = {"DOWNLOAD_DELAY": 0.5,"ITEM_PIPELINES": {'wenzhou_web.pipelines.MysqlPipeline': 320,'wenzhou_web.pipelines.MyFilePipeline': 321,},"DOWNLOADER_MIDDLEWARES": {'wenzhou_web.middlewares.WenzhouWebDownloaderMiddleware': 500,},}def parse(self, response):_response=response.texttag_list=re.findall("<span>.*?</span><b>&middot;</b><a href=\'(.*?)\'",_response)for tag in tag_list:url=self.base_url[0]+tag# print(url)yield scrapy.Request(url=url,callback=self.parse_detail)def parse_detail(self,response):# _response=response.text.encode('utf8')# print(_response)_response=response.textitem=WenzhouWebItem()pdf_url=re.findall(r'<a target="_blank" href="(.*?)"',_response)for u in pdf_url:u=u.split('pdf')[0]# print(u)#链接url="http://wzszjw.wenzhou.gov.cn"+u+"pdf"# print(url) item['file_urls']=[url]yield item# # #标题# # try:# # title=re.findall('<img src=".*?".*?><span style=".*?">(.*?)</span></a></p><meta name="ContentEnd">',_response)# # print(title[0])# # except:# # print('有异常!')
items.py

#
-*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WenzhouWebItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()# pass#链接file_urls=scrapy.Field()
middlewares.py

#
-*- coding: utf-8 -*-# Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.htmlfrom scrapy import signalsclass WenzhouWebSpiderMiddleware(object):# Not all methods need to be defined. If a method is not defined,# scrapy acts as if the spider middleware does not modify the# passed objects. @classmethoddef from_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.s = cls()crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)return sdef process_spider_input(self, response, spider):# Called for each response that goes through the spider# middleware and into the spider.# Should return None or raise an exception.return Nonedef process_spider_output(self, response, result, spider):# Called with the results returned from the Spider, after# it has processed the response.# Must return an iterable of Request, dict or Item objects.for i in result:yield idef process_spider_exception(self, response, exception, spider):# Called when a spider or process_spider_input() method# (from other spider middleware) raises an exception.# Should return either None or an iterable of Response, dict# or Item objects.passdef process_start_requests(self, start_requests, spider):# Called with the start requests of the spider, and works# similarly to the process_spider_output() method, except# that it doesn’t have a response associated.# Must return only requests (not items).for r in start_requests:yield rdef spider_opened(self, spider):spider.logger.info('Spider opened: %s' % spider.name)class WenzhouWebDownloaderMiddleware(object):# Not all methods need to be defined. If a method is not defined,# scrapy acts as if the downloader middleware does not modify the# passed objects. @classmethoddef from_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.s = cls()crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)return sdef process_request(self, request, spider):# Called for each request that goes through the downloader# middleware.# Must either:# - return None: continue processing this request# - or return a Response object# - or return a Request object# - or raise IgnoreRequest: process_exception() methods of# installed downloader middleware will be calledreturn Nonedef process_response(self, request, response, spider):# Called with the response returned from the downloader.# Must either;# - return a Response object# - return a Request object# - or raise IgnoreRequestreturn responsedef process_exception(self, request, exception, spider):# Called when a download handler or a process_request()# (from other downloader middleware) raises an exception.# Must either:# - return None: continue processing this exception# - return a Response object: stops process_exception() chain# - return a Request object: stops process_exception() chainpassdef spider_opened(self, spider):spider.logger.info('Spider opened: %s' % spider.name)
piplines.py

#
-*- coding: utf-8 -*-# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlfrom scrapy.conf import settings from scrapy.exceptions import DropItem from scrapy.pipelines.files import FilesPipeline import pymysql from urllib.parse import urlparse import scrapyclass WenzhouWebPipeline(object):def process_item(self, item, spider):return item# 数据保存mysql class MysqlPipeline(object):def open_spider(self, spider):self.host = settings.get('MYSQL_HOST')self.port = settings.get('MYSQL_PORT')self.user = settings.get('MYSQL_USER')self.password = settings.get('MYSQL_PASSWORD')self.db = settings.get(('MYSQL_DB'))self.table = settings.get('TABLE')self.client = pymysql.connect(host=self.host, user=self.user, password=self.password, port=self.port, db=self.db, charset='utf8')def process_item(self, item, spider):item_dict = dict(item)cursor = self.client.cursor()values = ','.join(['%s'] * len(item_dict))keys = ','.join(item_dict.keys())sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=self.table, keys=keys, values=values)try:if cursor.execute(sql, tuple(item_dict.values())): # 第一个值为sql语句第二个为 值 为一个元组print('数据入库成功!')self.client.commit()except Exception as e:print(e)print('数据已存在!')self.client.rollback()return itemdef close_spider(self, spider):self.client.close() #定义下载 class MyFilePipeline(FilesPipeline):def get_media_requests(self, item, info):for file_url in item['file_urls']:yield scrapy.Request(file_url)def item_completed(self, results, item, info):image_paths = [x['path'] for ok, x in results if ok]if not image_paths:raise DropItem("Item contains no file")item['file_urls'] = image_pathsreturn item
setting.py

#
-*- coding: utf-8 -*-# Scrapy settings for wenzhou_web project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'wenzhou_web'SPIDER_MODULES = ['wenzhou_web.spiders'] NEWSPIDER_MODULE = 'wenzhou_web.spiders'# mysql配置参数 MYSQL_HOST = "192.168.113.129" MYSQL_PORT = 3306 MYSQL_USER = "root" MYSQL_PASSWORD = "123456" MYSQL_DB = 'web_datas' TABLE = "web_wenzhou"# Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'wenzhou_web (+http://www.yourdomain.com)'# Obey robots.txt rules ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # 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', # 'Accept-Language': 'en', #}# Enable or disable spider middlewares # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'wenzhou_web.middlewares.WenzhouWebSpiderMiddleware': 543, #}# Enable or disable downloader middlewares # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = {'wenzhou_web.middlewares.WenzhouWebDownloaderMiddleware': 500, }# Enable or disable extensions # See https://doc.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #}# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = {'wenzhou_web.pipelines.WenzhouWebPipeline': 300,# 下载文件管道'scrapy.pipelines.MyFilePipeline': 1, }FILES_STORE = './download'# Enable and configure the AutoThrottle extension (disabled by default) # See https://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 https://doc.scrapy.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'

 

posted on 2018-09-25 16:50 五杀摇滚小拉夫 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lvjing/p/9700390.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_717856.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

小型网站项目完整部署流程(Windows操作系统)

前言 笔者近期接手一个第三方公司提供的基于Java web技术栈开发的后台前台项目。由于第一次做这么系统的开发&#xff0c;想着将项目开发的具体模块记录下来。从环境搭建到开发再到项目打包部署进行全开发链记录。本系列包含三篇博客&#xff0c;分别为环境搭建、项目开发、项…

小型网站开发环境搭建流程(Maven管理,Java技术栈)

前言 笔者近期接手一个第三方公司提供的基于Java web技术栈开发的后台前台项目。由于第一次做这么系统的开发&#xff0c;想着将项目开发的具体模块记录下来。从环境搭建到开发再到项目打包部署进行全开发链记录。本系列包含三篇博客&#xff0c;分别为环境搭建、项目开发、项…

小型网站项目完整部署流程(Linux操作系统——CentOS7.5)

前言 网络服务器以Linux操作系统的居多&#xff0c;因其天然的底层框架优势。笔者因为项目需求要在Linux操作系统服务上部署Java web项目&#xff0c;手头上没有该操作系统的服务器&#xff0c;因此使用虚拟机技术虚拟出一台CentOS7.5的虚拟服务器&#xff0c;并以此为基础进行…

如何编程登录有验证码的网站

看到论坛有人在问如何编程登录有验证码的网站题&#xff0c;于是专门研究了一下。文章后有源码下载地址。 注&#xff1a;验证码还是要人来辨认。 有几种处理办法&#xff0c;一是使用WebBrowser控件&#xff0c;一是使用WebClient或者WebRequest控件来处理。 本文中使用 Web…

网站漏洞渗透检测过程与修复方案

2019独角兽企业重金招聘Python工程师标准>>> 什么是网站渗透测试&#xff1f; 该如何做网站安全检测 网站的渗透测试简单来 说就是模拟攻击者的手法以及攻击手段去测试网站的漏洞&#xff0c;对网站进行渗透攻击测试&#xff0c;对网站的代码漏洞进行挖掘&#xff0…

m_Orchestrate learning system---网站的语言选择功能(中文英文)

m_Orchestrate learning system---网站的语言选择功能&#xff08;中文英文&#xff09; 一、总结 一句话总结&#xff1a;有两种方法&#xff0c;一是sessionjs端代码&#xff0c;而是sessionphp端代码。 推荐使用sessionphp端代码 用函数最方便&#xff0c;最简便&#xff0c…

如何用色彩制造出具有专业感的网站

如何用色彩制造出具有专业感的网站来源&#xff1a;yeeyan 作者&#xff1a;译&#xff1a;Srandy 发布时间&#xff1a; 2010-03-19 15:34:50是什么使得某个设计看起来协调、井然有序并且具有专业感&#xff1f;答案是&#xff1a;“色彩”。并不是所有的项目都需要用保守的黑…

如何让你的网站地址在发送到QQ朋友的时候显示绿色安全图标呢?...

今天教大家如何申请网址过QQ绿色安全打勾认证!网址获得了QQ安全认证过后就是把网址发给QQ好友或者QQ群的时候,我们的网址前面会有一个绿色的打勾标志! 首先介绍一下加V标示和不加V标示的区别&#xff1a; 加V绿标域名展示&#xff1a;官方认证&#xff0c;可放心访问。这种绿标…

安装好IIS后发布网站

首先&#xff0c;进行网站发布是需要IIS支持的&#xff0c;此处默认已经安装好IIS&#xff0c;并进行了Asp.net注册过程&#xff08;此步骤必需 &#xff0c;因为我是先安装的 .net 环境 &#xff0c;再安装的IIS&#xff09;。 其次&#xff0c;以下步骤可以方便指导新手如何…

安装好IIS后发布网站

首先&#xff0c;进行网站发布是需要IIS支持的&#xff0c;此处默认已经安装好IIS&#xff0c;并进行了Asp.net注册过程&#xff08;此步骤必需 &#xff0c;因为我是先安装的 .net 环境 &#xff0c;再安装的IIS&#xff09;。 其次&#xff0c;以下步骤可以方便指导新手如何…

推荐:总能找到一个你觉得最好的免费电子书下载网站

看书是获取知识的最佳途径之一&#xff0c;而读电子书更是我们IT人士的主要方式&#xff0c;在哪里可以获得自己需要的电子书呢&#xff1f;今天给大家推荐一些别人推荐的免费电子书下载网站&#xff0c;我相信其中总有一个是你所需要的&#xff0c;快去看看吧。当然&#xff0…

十周后,62%的PHP网站将运行在一个不受支持的PHP版本上

根据W3Techs的统计数据&#xff0c;目前约有78.9&#xff05;的网站使用PHP开发。\\但是&#xff0c;PHP 5.6.x的安全支持将在2018年12月31日正式停止&#xff0c;这标志着对古老的PHP 5.x分支版本的支持都将结束。\\也就是说&#xff0c;从明年开始&#xff0c;大约62&#xf…

[站长手记] 教训:title中关键词的位置对于网站排名的至关重要性

教训啊教训&#xff0c;本人的网站 www.tianqizx.cn 今天访问量创造了新低。 昨天还有500多个IP&#xff0c;今天就只有100多个了。 原因是来自百度的访问大幅减少&#xff0c;只有以前的10%了。 问题还是出在网站在标题 title上。 比如说&#xff0c;佛山南海天气 这个关键词&…

在线matlab网站

网址&#xff1a; http://octave-online.net/ 使用&#xff1a; 转载于:https://www.cnblogs.com/moonlightml/p/10238966.html

使用Mason为网站添加免费Captcha验证码

介绍&#xff1a; CAPTCHA 是“Completely Automated Public Turing test to tell Computers and Humans Apart”&#xff08;全自动区分计算机和人类的图灵测试&#xff09;的缩写&#xff0c;已由卡内基梅隆大学注册商标。是一种区分用户是计算机和人的公共全自动程序。在一…

使用Mason为网站添加免费Captcha验证码

介绍&#xff1a; CAPTCHA 是“Completely Automated Public Turing test to tell Computers and Humans Apart”&#xff08;全自动区分计算机和人类的图灵测试&#xff09;的缩写&#xff0c;已由卡内基梅隆大学注册商标。是一种区分用户是计算机和人的公共全自动程序。在一…

大型网站技术架构(1)

网站都是从小网站一步一步发展为大型网站的&#xff0c;而这之中的挑战主要来自于庞大的用户、安全环境恶劣、高并发的访问和海量的数据&#xff0c;任何简单的业务处理&#xff0c;一旦需要处理数以 P 计的数据和面对数以亿计的用户时&#xff0c;问题就会变的很棘手 下面我们…

网站被百度停止推广并提示网站存在安全风险,不宜推广的处理方案

2019独角兽企业重金招聘Python工程师标准>>> 春节刚过完&#xff0c;上班的第一天&#xff0c;公司网站被百度停止推广了&#xff0c;百度推广提示&#xff1a;您的url被百度杀毒提示存在网址安全风险&#xff0c;故物料不宜推广&#xff1b;若有异议&#xff0c;请…

网站安全演讲稿

主要包括HTML字符破坏、外部提交、SQL注入、XSS跨站攻击等几个方面。

网站安全演讲稿

主要包括HTML字符破坏、外部提交、SQL注入、XSS跨站攻击等几个方面。