这是一个自动生成API的神奇的python库

在学习做接口测试自动化的时候,我们往往会自己动手写一些简单的API,比如写一个简单的TODO API之类。

不过自己写API的时候经常需要造一些假数据,以及处理分页逻辑,开始的时候还觉得比较有意思,但久而久之就显得比较乏味了。

这时候你可能会想,有没有什么工具可以自动将一个线上的网站转化成简单的API呢?

这样的工具确实是存在的,而且不少,其中python语言中比较受欢迎的实现是https://github.com/gaojiuli/toapi项目,项目名称是toapi。

我们来简单体验一下这个库。

安装

首先安装。

pip install toapi
pip install cssselect

将重定向科技的课程列表页转化成API

http://www.itest.info/courses,这是重定向科技的课程列表页面,里面包含了目前我们所开设的全部课程。

现在我们将这个页面转化成API,这个API 返回每门课程的名称以及url。

from flask import request
from htmlparsing import Attr, Text
from toapi import Api, Item

api = Api()

@api.site('http://www.itest.info')
@api.list('.col-md-3')
@api.route('/courses?page={page}', '/courses')
@api.route('/courses', '/courses')
class Course(Item):
    url = Attr('a', 'href')
    title = Text('h4')

api.run(debug=True, host='0.0.0.0', port=12306)

运行

python app.py

查看结果

curl localhost:12306/courses

返回结果

{
    "Course": [
        {
            "title": "全栈测试开发班",
            "url": "/courses/9"
        },
        {
            "title": "性能测试从入门到精通班",
            "url": "/courses/7"
        },
        {
            "title": "接口自动化测试开发--Python班",
            "url": "/courses/6"
        },
        {
            "title": "Selenium自动化测试--Python班",
            "url": "/courses/2"
        }
    ]
}

官方例子

将hacknews网站转成API

from flask import request
from htmlparsing import Attr, Text
from toapi import Api, Item

api = Api()


@api.site('https://news.ycombinator.com')
@api.list('.athing')
@api.route('/posts?page={page}', '/news?p={page}')
@api.route('/posts', '/news?p=1')
class Post(Item):
    url = Attr('.storylink', 'href')
    title = Text('.storylink')


@api.site('https://news.ycombinator.com')
@api.route('/posts?page={page}', '/news?p={page}')
@api.route('/posts', '/news?p=1')
class Page(Item):
    next_page = Attr('.morelink', 'href')

    def clean_next_page(self, value):
        return api.convert_string('/' + value, '/news?p={page}', request.host_url.strip('/') + '/posts?page={page}')


api.run(debug=True, host='0.0.0.0', port=5000)

结果

{
  "Page": {
    "next_page": "http://127.0.0.1:5000/posts?page=2"
  },
  "Post": [
    {
      "title": "Mathematicians Crack the Cursed Curve",
      "url": "https://www.quantamagazine.org/mathematicians-crack-the-cursed-curve-20171207/"
    },
    {
      "title": "Stuffing a Tesla Drivetrain into a 1981 Honda Accord",
      "url": "https://jalopnik.com/this-glorious-madman-stuffed-a-p85-tesla-drivetrain-int-1823461909"
    }
  ]
}

总结

  • toapi使用非常简单,实际上就是把api的创建和爬虫结合起来了
  • toapi提供了比较完备的缓存机制,非首次访问的速度会很快
    有一定爬虫能力的测试同学可以用toapi来实现简单的mock server,但仅限于get接口
posted @ 2020-10-14 11:33  乙醇  阅读(806)  评论(0编辑  收藏  举报

友情链接 虫师的blog  测试教程网  重定向科技  省略