1
+ import time
2
+
1
3
from selenium import webdriver
2
4
from selenium .webdriver .chrome .options import Options
3
5
from selenium .webdriver .common .by import By
4
6
from selenium .webdriver .support .ui import WebDriverWait
5
7
from selenium .webdriver .support import expected_conditions as EC
6
8
from PIL import Image
7
9
import os
8
- import time
9
10
10
11
11
- # Initialize driver with options and cookie
12
12
def setup_driver (cookie_value ):
13
13
options = Options ()
14
14
options .add_argument ('--headless=new' )
@@ -19,42 +19,31 @@ def setup_driver(cookie_value):
19
19
return driver
20
20
21
21
22
- # Crop the screenshot using Pillow
23
22
def crop_image (input_path , output_path , crop_box = (0 , 0 , 640 , 621 )):
24
23
with Image .open (input_path ) as img :
25
24
cropped = img .crop (crop_box )
26
25
cropped .save (output_path )
27
26
28
27
29
- # Take screenshot of an element and trim it
30
28
def take_screenshot (driver , url , selector , output_name ):
31
29
driver .get (url )
32
- time .sleep (3 ) # Wait for the page to load completely
33
- try :
34
- # Wait for the element to be present and visible
35
- element = WebDriverWait (driver , 20 ).until (
36
- EC .presence_of_element_located ((By .CSS_SELECTOR , selector ))
37
- )
38
- temp_output = output_name # Directly save the temp screenshot as the final output
39
- element .screenshot (temp_output )
40
- crop_image (temp_output , output_name )
41
- except Exception as e :
42
- print (f"Error: Timeout or issue locating element with selector '{ selector } '" )
43
- print (f'Current URL: { driver .current_url } ' )
44
- print ('Page source:' )
45
- print (driver .page_source [:1000 ]) # Print first 1000 characters of source for debugging
46
- raise
30
+ element = WebDriverWait (driver , 10 ).until (
31
+ EC .presence_of_element_located ((By .CSS_SELECTOR , selector ))
32
+ )
33
+ temp_output = output_name # Directly save the temp screenshot as the final output
34
+ element .screenshot (temp_output )
35
+ crop_image (temp_output , output_name )
47
36
48
37
49
- # Main process
50
38
def main ():
51
39
cookie = os .getenv ('COOKIE' )
52
- if not cookie :
53
- raise ValueError ('COOKIE environment variable not set' )
54
40
driver = setup_driver (cookie )
55
41
try :
56
42
take_screenshot (
57
- driver , 'https://adventofcode.com/2024' , 'body > main > pre' , 'aoc-screenshot.png'
43
+ driver ,
44
+ 'https://adventofcode.com/2024' ,
45
+ 'body > main > pre' ,
46
+ 'aoc-screenshot.png' ,
58
47
)
59
48
finally :
60
49
driver .quit ()
0 commit comments