How to send files via post request in python similar to curl? (W3C validator)

130 Views Asked by At

I am trying to send a local html file from my computer to the https://validator.nu/ from W3C to validate it. I found this curl command which worked perfectly fine in terminal:

curl -H "Content-Type: text/html; charset=utf-8" \
    --data-binary @FILE.html \
    https://validator.w3.org/nu/?out=gnu

But how to do a post request in python equivalent to the mentioned curl command?

I have already tried the following but it did not work correctly.

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)

Can someone please help me in doing a request in python?

1

There are 1 best solutions below

0
SergiyKolesnikov On BEST ANSWER

You need to send the content of the file as binary data:

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)