python 模拟浏览器上传文件

import os, random, sys, requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = 'http://127.0.0.1/sendmsg'
argvstr = sys.argv[1:]
argv_dict = {}
for argv in argvstr :
    argv = str(argv).replace("\r\n" , "")
    DICT = eval(argv)
    argv_dict.update(DICT)

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0',
    'Referer': url
    }

multipart_encoder = MultipartEncoder(
    fields={
        'username': argv_dict['username'],
        'pwd': argv_dict['pwd'],
        'type': 'txt',
        'friendfield': argv_dict['friendfield'],
        'friend': argv_dict['friend'],
        'content': argv_dict['content'],
        'file': (os.path.basename(argv_dict['file']) , open(argv_dict['file'], 'rb'), 'application/octet-stream')
        #file为路径
        },
        boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1))
    )

headers['Content-Type'] = multipart_encoder.content_type
#请求头必须包含一个特殊的头信息,类似于Content-Type: multipart/form-data; boundary=${bound}

r = requests.post(url, data=multipart_encoder, headers=headers)
print(r.text)

转载于:https://www.cnblogs.com/testwu/p/8472472.html

你可能感兴趣的:(python 模拟浏览器上传文件)