如何在 Python 中模拟 post 表单来上传文件
2个回答
展开全部
额,这个其实查文档仔颤兆就可以实现,唯一有困难的地方在于你用的python版本,python2和3的实现库不太一样
python2里
import urllib2, urllib
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(url='http://www.xxx.net/',data=urllib.urlencode(data))
python3里
import urllib
url 洞贺= "http://www.xxx.net"
postdata = urllib.parse.urlencode({'name' : 'www', 'password' : '123456'})
res = urllib.request.urlopen(url,postdata)
改了一次代码排乱了,你自己凑念租活看吧
2017-05-05 · 知道合伙人互联网行家
关注
展开全部
#buld post body data
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'username')
data.append('jack'举拍歼)
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n'正冲 % 'mobile')
data.append('13800138000')
data.append('--%s' % boundary)
fr=open(r'/var/qr/b.png','rb')
data.append('Content-Disposition: form-data; name="%s"; filename="b.png"' % 'profile')
data.append('Content-Type: %s\r\n' % 'image/贺桥png')
data.append(fr.read())
fr.close()
data.append('--%s--\r\n' % boundary)
http_url='http://remotserver.com/page.php'
http_body='\r\n'.join(data)
try:
#buld http request
req=urllib2.Request(http_url, data=http_body)
#header
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
req.add_header('User-Agent','Mozilla/5.0')
req.add_header('Referer','http://remotserver.com/')
#post data to server
resp = urllib2.urlopen(req, timeout=5)
#get response
qrcont=resp.read()
print qrcont
except Exception,e:
print 'http error'
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'username')
data.append('jack'举拍歼)
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n'正冲 % 'mobile')
data.append('13800138000')
data.append('--%s' % boundary)
fr=open(r'/var/qr/b.png','rb')
data.append('Content-Disposition: form-data; name="%s"; filename="b.png"' % 'profile')
data.append('Content-Type: %s\r\n' % 'image/贺桥png')
data.append(fr.read())
fr.close()
data.append('--%s--\r\n' % boundary)
http_url='http://remotserver.com/page.php'
http_body='\r\n'.join(data)
try:
#buld http request
req=urllib2.Request(http_url, data=http_body)
#header
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
req.add_header('User-Agent','Mozilla/5.0')
req.add_header('Referer','http://remotserver.com/')
#post data to server
resp = urllib2.urlopen(req, timeout=5)
#get response
qrcont=resp.read()
print qrcont
except Exception,e:
print 'http error'
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询