hmrc87
hmrc87

Reputation: 354

Log in into website and download file with python requests

I have a website with a HTML-Form. After logging in it takes me to a start.php site and then redirects me to an overview.php.

I want to download files from that server... When I click on the download link of a ZIP-File the address behind the link is:

getimage.php?path="vol/img"&id="4312432"

How can I do that with requests? I tried to create a session and do the GET-Command with the right params... but the answer is just the website I would see when I'm not logged in.

c = requests.Session()
c.auth =('myusername', 'myPass')
request1 = c.get(myUrlToStart.PHP)
tex = request1.text

with open('data.zip', 'wb') as handle:
    request2 = c.get(urlToGetImage.Php, params=payload2, stream=True)
    print(request2.headers)
    for block in request2.iter_content(1024):
        if not block:
            break

        handle.write(block)

Upvotes: 4

Views: 10711

Answers (2)

drt
drt

Reputation: 817

Those who are looking for the same thing could try this...

import requests
import bs4

site_url = 'site_url_here'
userid = 'userid'
password = 'password'

file_url = 'getimage.php?path="vol/img"&id="4312432"' 
o_file = 'abc.zip'  

# create session
s = requests.Session()
# GET request. This will generate cookie for you
s.get(site_url)
# login to site.
s.post(site_url, data={'_username': userid, '_password': password})
# Next thing will be to visit URL for file you would like to download.
r = s.get(file_url)

# Download file
with open(o_file, 'wb') as output:
    output.write(r.content)
print(f"requests:: File {o_file} downloaded successfully!")

# Close session once all work done
s.close()

Upvotes: 3

Johannes Charra
Johannes Charra

Reputation: 29913

What you're doing is a request with basic authentication. This does not fill out the form that is displayed on the page.

If you know the URL that your form sends a POST request to, you can try sending the form data directly to this URL

Upvotes: 3

Related Questions