[英]How to send files via post request in python similar to curl? (W3C validator)
我正在嘗試將本地 html 文件從我的計算機發送到 W3C 的https://validator.nu/以驗證它。 我發現這個 curl 命令在終端中運行良好:
curl -H "Content-Type: text/html; charset=utf-8" \
--data-binary @FILE.html \
https://validator.w3.org/nu/?out=gnu
但是如何在 python 中進行與上述 curl 命令等效的發布請求?
我已經嘗試了以下方法,但它不能正常工作。
headers = {
'Content-Type': 'text/html',
'charset': 'utf-8',
}
url = "https://validator.w3.org/nu/?out=gnu"
files = {'upload_file': open('filename.html','rb')}
r = requests.post(url, files=files, data=data, headers=headers)
print(r.text)
有人可以幫我在 python 中提出請求嗎?
您需要將文件內容作為二進制數據發送:
import requests
headers = {
'Content-Type': 'text/html',
'charset': 'utf-8',
}
url = "https://validator.w3.org/nu/?out=gnu"
with open("filename.html", "rb") as f:
data = f.read()
r = requests.post(url, data=data, headers=headers)
print(r.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.