[Python] How to download a file from a website using python

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use python to download the following image file. The file is inside a website which requires a login to access, but there are 2 links to the file.

    below is secure link (which has the numbers taken out) https://assetplanner.com/files/ServiceRequest/616/img_20241021093256.jpg?token=#####

    below is publicly accessible link https://assetplanner.com/files/?f=e...9.d29xUb8q914dJmZnDCzTp5DY1x-PKIfAwhrpiq9kDUQ

    I've tried urlretrieve

    from urllib.request import urlretrieve
    url='https://tor.assetplanner.com/service_request?ID=230'
    filename = "changed.pdf"


    Which does nothing.

    I've tired urllib request

    import urllib.request
    url = 'https://imgs.xkcd.com/comics/python.png'
    urllib.request.urlretrieve(url, fr"C:\Users\location\xkcd_comic.png")


    which works when I take from the website in the example I found, but when i try it on the website i want

    import urllib.request
    url='https://assetplanner.com/files/ServiceRequest/153/changed.jpg?token=#####'
    urllib.request.urlretrieve(url, fr"C:\Users\location\xattempt.png")


    This one returns the 14 kb file, just named xattempt.png

    I've tried requests

    import requests
    url = 'https://tor.assetplanner.com/service_request?ID=616'
    r = requests.get(url)
    print(r.json())


    And requests another way

    import requests
    url = 'https://assetplanner.com/files/ServiceRequest/230/changed.pdf?token=#####'

    response = requests.get(url)
    file_Path = 'research_Paper_1.pdf'

    if response.status_code == 200:
    with open(file_Path, 'wb') as file:
    file.write(response.content)
    print('File downloaded successfully')
    else:
    print('Failed to download file')


    And requests another way

    import requests

    url = "https://assetplanner.com/files/ServiceRequest/230/changed.pdf?token=#####"
    query_parameters = {"downloadformat": "pdf"}
    response = requests.get(url, params=query_parameters)
    response.url
    response.ok
    response.status_code
    with open("#####.pdf", mode="wb") as file:
    file.write(response.content)


    But they all produce a 14kb document which doesn't work.

    I've tried wget

    import wget
    url = 'https://tor.assetplanner.com/service_request?ID=153'
    wget.download(url, 'img_#####.jpg')


    I end up with a 14 kg img_#####.jpg

    I know this is difficult, but is it obvious what I am doing wrong? Does anyone know a way to do it? I am using python to make a program where you type in the report numbers, and it will go to those reports, and then download the files, pdf or jpg.

    I thought it may have had something to do with me needing to log in, the the publicly accessible link doesn't need that.

    Continue reading...

Compartilhe esta Página