File size: 6,217 Bytes
6d8ab7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
896aea1
 
 
 
 
 
 
 
 
6d8ab7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Utilities Function for dealing with Selenium and generating PDF output"""

from io import BytesIO
from PyPDF2 import PdfMerger
from PIL import Image, ImageDraw, ImageFont
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options


def get_driver(production=True, width=1080, height=3840):
    """Initializes the driver with a tall headless window in production"""
    chrome_options = Options()
    if production:
        chrome_options.add_argument("--headless")
        chrome_options.add_argument(f"--window-size={width},{height}")
    return webdriver.Chrome(options=chrome_options)


def find_links_names(driver, partial_text):
    """Return all urls and full names of links that partially have the text"""
    links = driver.find_elements(By.PARTIAL_LINK_TEXT, partial_text)
    urls = [elem.get_attribute('href') for elem in links]
    names = [elem.text for elem in links]
    return urls, names


def click_button(driver, button_name):
    """Click the first button with the name attribute"""
    button = driver.find_element(By.NAME, button_name)
    button.click()


def click_link(driver, partial_text):
    """Click the first link that partially have the text"""
    link = driver.find_element(By.PARTIAL_LINK_TEXT, partial_text)
    link.click()


def get_html(driver, element):
    """Get an string of the innerHTML"""
    script = """
    var div = arguments[0];
    return div.innerHTML;
    """
    return driver.execute_script(script, element)


def get_html_with_images(driver, element):
    """Get an string of the innerHTML of the elements with embedded images"""
    script = """
    function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            return canvas.toDataURL("image/png");
    }
    var div = arguments[0];
    var images = div.getElementsByTagName('img');
    for (var i = 0; i < images.length; i++) {
            var img = images[i];
            var src = img.src;
            if (src.startsWith('http')) {
                    img.src = getBase64Image(img);
            }
    }
    return div.innerHTML;
    """
    return driver.execute_script(script, element)


def bytes_to_image(img_bytes: bytes) -> Image:
    """Reads the bytes and returns a PIL.Image"""
    return Image.open(BytesIO(img_bytes))


def image_to_bytes(img, f_type='JPEG', quality=95):
    """Convert a PIL Image to its bytes representation"""
    bytesio = BytesIO()
    img.save(bytesio, format=f_type, quality=quality)
    bytesio.seek(0)
    return bytesio.getvalue()


def take_full_div_screenshot(driver, div):
    """Takes the screenshot of the whole div, uses zoom,
    resolution may be bad if too big"""
    div_h = driver.execute_script("return arguments[0].offsetHeight;", div)
    div_w = driver.execute_script("return arguments[0].offsetWidth;", div)
    window_height = driver.execute_script("return window.innerHeight;")
    window_width = driver.execute_script("return window.innerWidth;")
    zoom_level = min(window_height / div_h, window_width / div_w, 1)
    driver.execute_script(f"document.body.style.zoom = '{zoom_level}'")
    driver.execute_script("arguments[0].scrollIntoView();", div)
    im = bytes_to_image(driver.get_screenshot_as_png())
    div_x = int(driver.execute_script("return arguments[0].getBoundingClientRect().left;", div))
    div_y = int(driver.execute_script("return arguments[0].getBoundingClientRect().top;", div))
    im = im.crop((div_x, div_y, div_x + int(div_w * zoom_level), div_y + int(div_h * zoom_level)))
    if zoom_level != 1:
        im = im.resize((div_w, div_h), Image.LANCZOS)
    driver.execute_script("document.body.style.zoom = '1'")
    return im


def hide_between_start_end(driver, parent, start: str, end: str, visible=False):
    """Hides all children of the parent that are between start (inclusive) to end (text representation)"""
    children = parent.get_property('children')
    start_index = None
    end_index = None
    for i, child in enumerate(children):
        if child.text.strip() == start:
            start_index = i
        elif child.text.strip() == end:
            end_index = i
            break
    assert start_index is not None
    assert end_index is not None
    for i in range(end_index - 1, start_index-1, -1):
        driver.execute_script(f"arguments[0].style.display = '{'' if visible else 'none'}';\
                arguments[0].style.visibility = '{'' if visible else 'hidden'}';", children[i])


def copy_element_as_first_child(driver, source_locator, destination_locator):
    """Copies the source_locator to be the first child of the destination_locator"""
    script = """
    var source = arguments[0];
    var destination = arguments[1];
    var clone = source.cloneNode(true);
    destination.insertBefore(clone, destination.firstChild);
    """
    driver.execute_script(script, source_locator, destination_locator)


def create_pdf_from_images(images_bytes, output_pdf_path, dpi=100, quality=90):
    """Create a PDF file with one image per page from the images_bytes list"""
    pdf_merger = PdfMerger()
    for img_bytes in images_bytes:
        img = bytes_to_image(img_bytes)
        pdf_buffer = BytesIO()
        img.save(pdf_buffer, format='PDF', resolution=dpi, quality=quality)
        pdf_buffer.seek(0)
        pdf_merger.append(pdf_buffer)
    pdf_merger.write(output_pdf_path)


def create_image_from_text(text, size=(800, 200), as_bytes=True):
    """Renders a text"""
    image = Image.new('RGB', size, color='white')
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("DejaVuSans.ttf", 28)
    text_bbox = draw.textbbox((0, 0), text, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    position = ((size[0]-text_width)/2, (size[1]-text_height)/2)
    draw.text(position, text, fill="black", font=font)
    draw.rectangle([0, 0, size[0]-1, size[1]-1], outline="black")
    if as_bytes:
        return image_to_bytes(image)
    return image