最近Hackmd有進行更動,原本在imgur的圖片都會被轉換到https://hackmd.io/uploads/xxx.png 的網址上。但是我有備份的習慣,因此會利用python來下載圖片。但是近期更動到hackmd伺服器上後會出現Error: HTTP Error 403: Forbidden,想要各位請問一下有甚麼方法可以解決嗎?(Hackmd有提供API可以使用) 謝謝各位!
以下為我原本的code:
import os
import urllib.request
from urllib.parse import urlparse
def download_image(url, output_directory):
try:
parsed_url = urlparse(url)
file_name = os.path.basename(parsed_url.path)
file_path = os.path.join(output_directory, file_name)
if os.path.exists(file_path):
print(f"File already exists: {file_path}")
return
urllib.request.urlretrieve(url, file_path)
print(f"Downloaded {file_name}")
except Exception as e:
print(f"Failed to download {url} -> Error: {str(e)}")
file_path = "image_urls.txt"
output_directory = "downloaded_images"
if not os.path.exists(output_directory):
os.makedirs(output_directory)
with open(file_path, "r") as file:
urls = file.readlines()
urls = [url.strip() for url in urls]
for url in urls:
download_image(url, output_directory)