1. 程式人生 > 實用技巧 >這是一個自動生成API的神奇的python庫

這是一個自動生成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介面