Arkm20 commited on
Commit
3b74c54
·
verified ·
1 Parent(s): 260a4d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -10
app.py CHANGED
@@ -37,25 +37,34 @@ def fetch_html(url: str):
37
  return {"error": str(e)}
38
 
39
  @app.get("/download")
40
- def download_screenshot(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
- # Take a screenshot of the page once content is fully loaded
54
- screenshot = page.screenshot(full_page=True) # Set full_page=True to capture the entire page
55
- browser.close()
56
-
57
- # Return the screenshot as a response with image/png content type
58
- return Response(content=screenshot, media_type="image/png")
 
 
 
 
 
 
 
 
 
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