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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -14
app.py CHANGED
@@ -42,29 +42,27 @@ def download_image(url: str):
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
 
 
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
+ # Select the first image on the page
54
+ img_element = page.query_selector("img")
55
+
56
+ if img_element:
57
+ # Take a screenshot of the first image element
58
+ screenshot = img_element.screenshot()
 
 
59
  browser.close()
60
 
61
+ # Return the image as a response
62
+ return Response(content=screenshot, media_type="image/png")
63
  else:
64
  browser.close()
65
+ return {"error": "No image found on the page"}
66
  except Exception as e:
67
  return {"error": str(e)}
68