|
1 | 1 | import asyncio |
2 | 2 | import json |
3 | 3 |
|
| 4 | +import aiofiles |
4 | 5 | from bs4 import BeautifulSoup |
5 | 6 |
|
6 | 7 | from pydoll import exceptions |
7 | 8 | from pydoll.commands.dom import DomCommands |
8 | 9 | from pydoll.commands.input import InputCommands |
| 10 | +from pydoll.commands.page import PageCommands |
9 | 11 | from pydoll.commands.runtime import RuntimeCommands |
10 | 12 | from pydoll.connection import ConnectionHandler |
11 | 13 | from pydoll.constants import Scripts |
12 | 14 | from pydoll.mixins.find_elements import FindElementsMixin |
| 15 | +from pydoll.utils import decode_image_to_bytes |
13 | 16 |
|
14 | 17 |
|
15 | 18 | class WebElement(FindElementsMixin): |
@@ -125,7 +128,7 @@ async def get_bounds_using_js(self) -> list: |
125 | 128 | response = await self._execute_script( |
126 | 129 | Scripts.BOUNDS, return_by_value=True |
127 | 130 | ) |
128 | | - return response['result']['result']['value'] |
| 131 | + return json.loads(response['result']['result']['value']) |
129 | 132 |
|
130 | 133 | async def _execute_script( |
131 | 134 | self, script: str, return_by_value: bool = False |
@@ -170,6 +173,30 @@ async def _is_element_on_top(self): |
170 | 173 | ) |
171 | 174 | return result['result']['result']['value'] |
172 | 175 |
|
| 176 | + async def get_screenshot(self, path: str): |
| 177 | + """ |
| 178 | + Takes a screenshot of the element. |
| 179 | +
|
| 180 | + Args: |
| 181 | + path (str): The path where the screenshot will be saved. |
| 182 | + """ |
| 183 | + bounds = await self.get_bounds_using_js() |
| 184 | + clip = { |
| 185 | + 'x': bounds['x'], |
| 186 | + 'y': bounds['y'], |
| 187 | + 'width': bounds['width'], |
| 188 | + 'height': bounds['height'], |
| 189 | + 'scale': 1, |
| 190 | + } |
| 191 | + screenshot = await self._connection_handler.execute_command( |
| 192 | + PageCommands.screenshot( |
| 193 | + format='png', clip=clip |
| 194 | + ) |
| 195 | + ) |
| 196 | + async with aiofiles.open(path, 'wb') as file: |
| 197 | + image_bytes = decode_image_to_bytes(screenshot['result']['data']) |
| 198 | + await file.write(image_bytes) |
| 199 | + |
173 | 200 | async def get_element_text(self) -> str: |
174 | 201 | """ |
175 | 202 | Retrieves the text of the element. |
@@ -241,7 +268,6 @@ async def click(self, x_offset: int = 0, y_offset: int = 0): |
241 | 268 | ) |
242 | 269 | except KeyError: |
243 | 270 | element_bounds = await self.get_bounds_using_js() |
244 | | - element_bounds = json.loads(element_bounds) |
245 | 271 | position_to_click = ( |
246 | 272 | element_bounds['x'] + element_bounds['width'] / 2, |
247 | 273 | element_bounds['y'] + element_bounds['height'] / 2, |
|
0 commit comments