1234567891011121314151617181920212223242526272829303132333435 |
- import io
- from PIL import Image
- from selenium.webdriver.common.action_chains import ActionChains
- from selenium.webdriver.common.keys import Keys
- def compress_image(image_path, output_path, quality=90, resize=None):
- """压缩图片并保存到指定路径。
- :param image_path: 原始图片路径
- :param output_path: 压缩后图片路径
- :param quality: 压缩质量,范围1-100,默认90,值越小图片越小但质量越差
- """
- img = Image.open(image_path)
- if resize:
- img.thumbnail(resize)
- img = Image.open(image_path)
- img.save(output_path, optimize=True, quality=quality)
- def scroll_to_element(driver, element):
- """滚动到指定元素位置。"""
- driver.execute_script("arguments[0].scrollIntoView();", element)
- def capture_element_screenshot(driver, element, filename):
- """Captures screenshot of the given element and saves it."""
- location = element.location
- size = element.size
- screenshot = driver.get_screenshot_as_png() # 获取整个页面的截图
- image = Image.open(io.BytesIO(screenshot))
- # 计算截图中元素对应的位置并裁剪
- left = location['x']
- top = location['y']
- right = location['x'] + size['width']
- bottom = location['y'] + size['height']
- cropped_image = image.crop((left, top, right, bottom)) # 注意这里的顺序是(left, top, right, bottom),可能需要调整为(left, top, right, bottom)取决于坐标系
- cropped_image.save(filename)
|