Update app.py
Browse files
app.py
CHANGED
@@ -37,25 +37,34 @@ def fetch_html(url: str):
|
|
37 |
return {"error": str(e)}
|
38 |
|
39 |
@app.get("/download")
|
40 |
-
def
|
41 |
try:
|
42 |
with sync_playwright() as p:
|
43 |
browser = p.chromium.launch(headless=True)
|
44 |
page = browser.new_page()
|
45 |
-
|
46 |
# Set custom headers before navigating to the page
|
47 |
headers = get_custom_headers(url)
|
48 |
page.set_extra_http_headers(headers)
|
49 |
-
|
50 |
# Navigate to the URL and wait for network idle
|
51 |
page.goto(url, timeout=15000, wait_until="networkidle")
|
52 |
-
|
53 |
-
#
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
except Exception as e:
|
60 |
return {"error": str(e)}
|
61 |
|
|
|
37 |
return {"error": str(e)}
|
38 |
|
39 |
@app.get("/download")
|
40 |
+
def download_image(url: str):
|
41 |
try:
|
42 |
with sync_playwright() as p:
|
43 |
browser = p.chromium.launch(headless=True)
|
44 |
page = browser.new_page()
|
45 |
+
|
46 |
# Set custom headers before navigating to the page
|
47 |
headers = get_custom_headers(url)
|
48 |
page.set_extra_http_headers(headers)
|
49 |
+
|
50 |
# Navigate to the URL and wait for network idle
|
51 |
page.goto(url, timeout=15000, wait_until="networkidle")
|
52 |
+
|
53 |
+
# Locate the first <img> element on the page
|
54 |
+
image_element = page.query_selector("img") # You can adjust the selector to target a specific image
|
55 |
+
|
56 |
+
if image_element:
|
57 |
+
# Get the image's source URL
|
58 |
+
img_url = image_element.get_attribute("src")
|
59 |
+
image_data = page.request.get(img_url).body # Fetch the image data from the source URL
|
60 |
+
|
61 |
+
browser.close()
|
62 |
+
|
63 |
+
# Return the image data as a response with image/jpeg or image/png, depending on the image type
|
64 |
+
return Response(content=image_data, media_type="image/jpeg" if img_url.endswith(".jpg") else "image/png")
|
65 |
+
else:
|
66 |
+
browser.close()
|
67 |
+
return {"error": "No image found on the page."}
|
68 |
except Exception as e:
|
69 |
return {"error": str(e)}
|
70 |
|