compress_image.py 1.4 KB

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