本系列教程咱們將使用python實現一些簡單的測試工具,爲了儘量的簡單,咱們的工具以命令行工具爲主。node
本系列教程使用的python版本是3.6.3。python
這一節咱們實現簡單的命令行發送get請求的工具,使用方式以下:git
python get.py www.v2ex.com/api/nodes/show.json\?name\=python 接口地址: http://www.v2ex.com/api/nodes/show.json?name=python 狀態碼: 200 Headers: Date : Tue, 10 Jul 2018 07:06:12 GMT Content-Type : application/json;charset=UTF-8 Transfer-Encoding : chunked Connection : keep-alive Vary : Accept-Encoding X-Rate-Limit-Remaining : 119 Expires : Tue, 10 Jul 2018 08:03:49 GMT Server : Galaxy/3.9.8.1 Etag : W/"76a33d25372411dc6fa4190a5cf9679caa0edc2a" X-Rate-Limit-Reset : 1531209600 Cache-Control : max-age=3600 X-Rate-Limit-Limit : 120 Google : XY Content-Encoding : gzip Strict-Transport-Security : max-age=31536000 { "id" : 90, "name" : "python", "url" : "https://www.v2ex.com/go/python", "title" : "Python", "title_alternative" : "Python", "topics" : 9530, "stars" : 6601, "header" : "這裏討論各類 Python 語言編程話題,也包括 Django,Tornado 等框架的討論。這裏是一個可以幫助你解決實際問題的地方。", "footer" : null, "created" : 1278683336, "avatar_mini" : "//cdn.v2ex.com/navatar/8613/985e/90_mini.png?m=1531131631", "avatar_normal" : "//cdn.v2ex.com/navatar/8613/985e/90_normal.png?m=1531131631", "avatar_large" : "//cdn.v2ex.com/navatar/8613/985e/90_large.png?m=1531131631" }
主要使用場景是快速訪問http的api接口,查看狀態碼,響應頭以及響應內容。github
簡單起見,咱們會用到requests庫。安裝文檔在這裏。編程
import requests from sys import argv USAGE = ''' USAGE: python get.py https://api.github.com ''' if len(argv) != 2: print(USAGE) exit() script_name, url = argv if url[:4] != 'http': url = 'http://' + url r = requests.get(url) print(f"接口地址: {url}\n") print(f"狀態碼: {r.status_code}\n") print(f"Headers:") for key, value in r.headers.items(): print(f"{key} : {value}") print(r.text)
Content-Type: application/json
的headers,這段代碼該如何修改github地址json