swagger上的接口写入数据库
一、依赖
virtualenv -p python3.6 xx
pip install scrapy
pip install pymysql
二、
1、创建项目和spider1
scrapy startproject scraw_swagger
scrapy genspider spider1 xxx.com (执行之后在项目的spiders目录下会生成一个spider1.py的文件)
以下代码主要实现了将swagger的第一级目录爬下来存在一个叫:interfaces_path的文件下
# -*- coding: utf-8 -*-
import scrapy
import json
from scraw_swagger import settings class Spider1Spider(scrapy.Spider): name = 'spider1'
allowed_domains = ['xxx.com'']
scrawl_domain = settings.interface_domain+'/api-docs'
start_urls = [scrawl_domain] def parse(self, response):
# 调试代码
# filename = 'mid_link'
# open(filename, 'wb').write(response.body)
# /////////
response = response.body
response_dict = json.loads(response)
apis = response_dict['apis']
n = len(apis)
temppath = []
i = 0 domain = settings.interface_domain+'/api-docs'
filename = 'interfaces_path'
file = open(filename, 'w')
for i in range(0, n):
subapi = apis[i]
path = subapi['path']
path = ','+domain + path
temppath.append(path)
file.write(path)
2、创建spider2
scrapy genspider spider2 xxx.com (执行之后在项目的spiders目录下会生成一个spider2.py的文件)
以下代码主要实现了获取interfaces_path的文件下的地址对应的内容
# # -*- coding: utf-8 -*-
import scrapy
from scraw_swagger.items import ScrawSwaggerItem
import json
from scraw_swagger import settings class Spider2Spider(scrapy.Spider):
name = 'spider2'
allowed_domains = ['xxx.com']
file = open('interfaces_path', 'r')
file = file.read()
list_files = []
files = file.split(',')
n = len(files)
for i in range(1, n):
file = files[i]
list_files.append(file)
start_urls = list_files def parse(self, response):
outitem = ScrawSwaggerItem()
out_interface = []
out_domain = []
out_method = []
out_param_name = []
out_data_type = []
out_param_required = []
# 调试代码
# filename = response.url.split("/")[-1]
# open('temp/'+filename, 'wb').write(response.body)
# ///////
response = response.body
response_dict = json.loads(response)
items = response_dict['apis']
items_len = len(items)
for j in range(0, items_len):
path = items[j]['path']
# interface组成list
operations = items[j]['operations'][0]
method = operations['method']
parameters = operations['parameters']
parameters_len = len(parameters)
param_name = []
param_required = []
data_type = []
for i in range(0, parameters_len):
name = parameters[i]['name']
param_name.append(name)
required = parameters[i]['required']
param_required.append(required)
type = parameters[i]['type']
data_type.append(type) out_interface.append(path)
interface_domain = settings.interface_domain
out_domain.append(interface_domain)
out_method.append(method)
out_data_type.append(data_type)
out_param_name.append(param_name)
out_param_required.append(param_required) outitem['interface'] = out_interface
outitem['domain'] = out_domain
outitem['method'] = out_method
outitem['param_name'] = out_param_name
outitem['param_required'] = out_param_required
outitem['data_type'] = out_data_type
yield outitem
3、settings.py文件
# -*- coding: utf-8 -*- # Scrapy settings for scraw_swagger 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 interface_domain = 'test'
token = 'test' # 调试代码
# interface_domain = 'http://xxxx..net'
# token = 'xxxxxx'
# /////////////// BOT_NAME = 'scraw_swagger' SPIDER_MODULES = ['scraw_swagger.spiders']
NEWSPIDER_MODULE = 'scraw_swagger.spiders' FEED_EXPORT_ENCODING = 'utf-8' # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'scraw_swagger (+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 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 = {
# 'scraw_swagger.middlewares.ScrawSwaggerSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'scraw_swagger.middlewares.ScrawSwaggerDownloaderMiddleware': 543,
#} # 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 = {
'scraw_swagger.pipelines.ScrawSwaggerPipeline': 300,
# 'scraw_swagger.pipelines.MysqlTwistedPipline': 200,
} # 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' MYSQL_HOST = ''
MYSQL_DBNAME = ''
MYSQL_USER = ''
MYSQL_PASSWD = ''
MYSQL_PORT = 3306
4、存入数据库。编写pipelines.py文件。提取返回的item,并将对应的字段存入数据库
# -*- coding: utf-8 -*-
import pymysql
from scraw_swagger import settings
from twisted.enterprise import adbapi
import pymysql.cursors
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class ScrawSwaggerPipeline(object):
def process_item(self, item, spider):
try:
# 插入数据sql
sql = """
insert into interfaces (domain, interface, method, param_name ,data_type, param_required)
VALUES (%s, %s, %s, %s, %s, %s)
"""
domain = item['domain']
n = len(domain)
for i in range(0, n):
domain = str(item['domain'][i])
interface = str(item["interface"][i])
method = str(item["method"][i])
param_name = str(item["param_name"][i])
data_type = str(item["data_type"][i])
param_required = str(item["param_required"][i])
a = (domain, interface, method, param_name, data_type, param_required)
self.cursor.execute(sql, a)
self.connect.commit()
except Exception as error:
# 出现错误时打印错误日志
print(error)
# self.connect.close()
return item def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host=settings.MYSQL_HOST,
db=settings.MYSQL_DBNAME,
user=settings.MYSQL_USER,
passwd=settings.MYSQL_PASSWD,
port=settings.MYSQL_PORT,
charset='utf8',
use_unicode=True) # 通过cursor执行增删查改
self.cursor = self.connect.cursor()
swagger上的接口写入数据库的更多相关文章
- 开机后将sim/uim卡上的联系人写入数据库
tyle="margin:20px 0px 0px; font-size:14px; line-height:26px; font-family:Arial; color:rgb(51,51 ...
- 通过POI实现上传EXCEL的批量读取数据写入数据库
最近公司新增功能要求导入excel,并读取其中数据批量写入数据库.于是就开始了这个事情,之前的文章,记录了上传文件,本篇记录如何通过POI读取excel数据并封装为对象上传. 上代码: 1.首先这是一 ...
- c#上传文件并将word pdf转化成txt存储并将内容写入数据库
c#上传文件并将word pdf转化成txt存储并将内容写入数据库 using System; using System.Data; using System.Configuration; using ...
- Django上传excel表格并将数据写入数据库
前言: 最近公司领导要统计技术部门在各个业务条线花费的工时百分比,而 jira 当前的 Tempo 插件只能统计个人工时.于是就写了个报表工具,将 jira 中导出的个人工时excel表格 导入数据库 ...
- c#WebApi使用form表单提交excel,实现批量写入数据库
思路:用户点击下载模板按钮,获取到excel模板,然后向里面填写数据保存.from表单提交的时候选择保存好的excel,实现数据的批量导入过程 先把模板放在服务器的项目目录下面:如 模板我一般放在:F ...
- 使用log4j让日志写入数据库
之前做的一个项目有这么个要求,在日志管理系统里,需要将某些日志信息存储到数据库里,供用户.管理员查看分析.因此我就花了点时间搞了一下这一功能,各位请看. 摘要:我们知道log4j能提供强大的可配置的记 ...
- Excel 导入到Datatable 中,再使用常规方法写入数据库
首先呢?要看你的电脑的office版本,我的是office 2013 .为了使用oledb程序,需要安装一个引擎.名字为AccessDatabaseEngine.exe.这里不过多介绍了哦.它的数据库 ...
- SQLBulkCopy使用实例--读取Excel写入数据库/将 Excel 文件转成 DataTable
MS SQL Server 提供一个称为 bcp 的流行的命令提示符实用工具,用于将数据从一个表移动到另一个表(表可以在不同服务器上). SqlBulkCopy 类允许编写提供类似功能的托管代码解决方 ...
- thinkphp + 美图秀秀api 实现图片裁切上传,带数据库
思路: 1.数据库 创建test2 创建表img,字段id,url,addtime 2.前台页: 1>我用的是bootstrap 引入必要的js,css 2>引入美图秀秀的js 3.后台: ...
随机推荐
- (6)MySQL进阶篇SQL优化(MyISAM表锁)
1.MySQL锁概述 锁是计算机协调多个进程或线程并发访问某一资源的机制.在数据库中,除传统的计算资源 (如 CPU.RAM.I/O 等)的抢占以外,数据也是一种供许多用户共享的资源.如何保证数 据并 ...
- 【Java】 5.0 判断与转换
[概述] 在if/条件语句中,我们已经谈及判断了,这次将详细讲讲一些逻辑判断 基本逻辑 &:且,And,需要二者均为True |:或,Or ,需要二者其一为False即可 ^:异或,XOE,两 ...
- 前端 JS 问题记录
立即执行函数 !function(){}() function 前面增加符号 ! ~ + - 之类,都是告诉浏览器自动执行这个匿名函数,因为这些符号的运算级别都是高的 (function(){... ...
- 死磕Spring之AOP篇 - Spring AOP自动代理(一)入口
该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读. Spring 版本:5.1 ...
- 【随笔】C++类静态成员变量初始化引发的惨痛教训
事情是这样的,我在某个类中声明了一个静态的map成员, 文件名暂且称之为 xxx.h 然后在 xxx.cc 中全局定义了这个东西,静态成员在类里面只是声明,需要在外边被定义才有内存 然后又在main. ...
- 墙裂推荐:这可能是CAP理论的最好现实解释
这篇文章蓝本:http://ksat.me/a-plain-english-introduction-to-cap-theorem 经过小码甲意译.原创配图, 干到让你怀孕. 你可能经常听到CAP定理 ...
- 5. Mybatis UPDATE更新,DELETE删除
案例: 1. update <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper ...
- Scrapy 爬虫项目框架
1. Scrapy 简介 2. Scrapy 项目开发介绍 3. Scrapy 项目代码示例 3.1 setting.py:爬虫基本配置 3.2 items.py:定义您想抓取的数据 3.3 spid ...
- Docker怎么实现容器之间的通信?
//TODO 参考资料: https://developer.aliyun.com/article/55912 https://blog.csdn.net/u011541946/article/det ...
- UVA10341解方程(二分)
题意: 给你一个方程 F[x] = pe^-x + qsin(x) + rcos(x) + stan(x) + tx^2 + u = 0(0<=p,r<=20,-20<= ...