我想發一個POST請求,使用python将檔案上傳到Web服務(并得到響應).例如,我可以使用curl執行以下POST請求:
curl -F "[email protected]" -F output=json http://jigsaw.w3.org/css-validator/validator
如何使用python urllib / urllib2發出相同的請求?我到目前為止最接近的是:
with open("style.css", 'r') as f:
content = f.read()
post_data = {"file": content, "output": "json"}
request = urllib2.Request("http://jigsaw.w3.org/css-validator/validator", \
data=urllib.urlencode(post_data))
response = urllib2.urlopen(request)
我從上面的代碼中得到了HTTP Error 500.但是因為我的curl指令成功了,我的python請求一定是錯的?
我對這個話題很陌生,如果菜鳥問題有很簡單的答案或錯誤,請原諒我.在此先感謝您的所有幫助!
解決方法:
我個人認為你應該考慮requests庫釋出檔案.
url = 'http://jigsaw.w3.org/css-validator/validator'
files = {'file': open('style.css')}
response = requests.post(url, files=files)
标簽:python,post,http,urllib,urllib2
來源: https://codeday.me/bug/20190930/1835645.html