根據文字中每一行資料生成json再進行url訪問
阿新 • • 發佈:2019-01-04
# -*- coding: utf-8 -*- Usage: add-post <session> <inputfile> """ from docopt import docopt import requests import json import os import time from datetime import datetime if __name__ == '__main__': # 將繫結互動引數 arguments = docopt(__doc__) session = arguments['<session>'] inputfile = arguments['<inputfile>'] url = "http://xxx" # print(os.getcwd()) if os.path.isfile(inputfile) == False: print("找不到此檔案:{}".format(inputfile)) exit(0) # Content-Type型別需要設定為:application/json headers = {"Content-Type": "application/json", "Cookie": "CNAF_SESSIONID_V2017={}".format(session)} a = datetime.now() with open(inputfile, mode='r', encoding='gbk') as f: for line in f: # split()預設以空格分隔,此處根據文件中資料進行分隔 list_line = line.split() time.sleep(1) data_str = {'name': list_line[0], 'remark': list_line[1]} # 需要將str檔案轉換成json物件 r = requests.post(url, json.dumps(data_str), headers=headers) print(r.text) b = datetime.now() # print("{}:{}".format(a, b)) print('Cost {} seconds'.format((b - a).seconds))
瀏覽器原生態form表單提交application/x-www-form-urlencoded
# -*- coding: utf-8 -*- """ Usage: miguQuery <session> <class_id> <inputfile> <outputfile> """ from docopt import docopt import requests import json import os import time from datetime import datetime if __name__ == '__main__': # 將繫結互動引數 arguments = docopt(__doc__) session = arguments['<session>'] class_id = arguments['<class_id>'] inputfile = arguments['<inputfile>'] outputfile = arguments['<outputfile>'] url = "http://xxx" if os.path.isfile(inputfile) == False: print("找不到此檔案:{}".format(inputfile)) exit(0) if os.path.isfile(outputfile) == True: print("檔案: {} 已經存在,請儲存為另一個名字".format(outputfile)) exit(0) headers = {"Cookie": "CNAF_SESSIONID_V2017={}".format(session)} a = datetime.now() with open(inputfile, mode='r', encoding='utf-8') as f: for line in f: # split()預設以空格分隔,此處根據文件中資料進行分隔 time.sleep(1) data_str = {'classId': class_id, 'content': line} r = requests.post(url, data_str, headers=headers) print(r.text) b = datetime.now() # print("{}:{}".format(a, b)) print('Cost {} seconds'.format((b - a).seconds))