José Guedes
José Guedes

Reputation: 400

What I am doing wrong when trying to upload a file to a form using Python and Requests?

I am learning web scraping with Python and I am trying to upload an image to a form for the first time. The website is aliseeks.com and I am not sure the URL I am trying to upload it to is the right one but it's the only one I found when inspecting the site.

import requests
from bs4 import BeautifulSoup

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
        'Accept-Encoding': 'gzip, deflate',
        'DNT': '1',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
    }

def search(image):
    s = requests.Session()

    result = requests.post(url='https://api.aliseeks.com/upload/image', files = image, headers = headers)
    
    print (result.text)
    
    
def main():
    file = {'upload_file': open('C:\\Users\\Ze\\Pictures\\Ajahn Brahm.jpg','rb')}
    search(file)
    
if __name__ == "__main__":
    main()

The error I'm getting is the following:

[{"exception":"MissingServletRequestPartException","message":"Required request part 'file' is not present"}]

Thanks a lot!

Upvotes: 0

Views: 548

Answers (1)

hangonstack
hangonstack

Reputation: 187

According to the docs for the requests library, specifically, the following part:

>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)

files is a dictionary with the field 'file'. So maybe try replace 'upload_file' with 'file' instead?

Upvotes: 1

Related Questions