简体   繁体   English

Python PIL 保存的黑色图像

[英]Python PIL saved black image

i'm trying to get screenshot of phone element in site.我正在尝试获取网站中电话元素的屏幕截图。 I save the screenshot of entire page, get element coordinates and crop screenshot in phone element place.我保存整个页面的屏幕截图,获取元素坐标并在手机元素位置裁剪屏幕截图。 But after cropping i got black image.但裁剪后我得到了黑色图像。 I don't understand why, and how i can fixe it.我不明白为什么,以及如何修复它。

My code:我的代码:

# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.proxy import *
import time
from PIL import Image

driver = webdriver.Chrome(executable_path='chromedriver')
driver.get('https://www.avito.ru/moskva/audio_i_video/televizor_samsung_i_tumba_iz_stekla_k_nemu_838296913')
button = driver.find_element_by_xpath('//*[@id="i_contact"]/div[3]/div/span[1]/span')
button.click()
time.sleep(4)
element = driver.find_element_by_xpath('//*[@id="i_contact"]/div[3]/div/span[1]')
location = element.location
size = element.size
driver.save_screenshot('screenshot.png')
driver.quit()

im = Image.open('screenshot.png')

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']


im = im.crop((left, top, right, bottom))
im.save('screenshot.png')

Screenshot after Selenium save: Selenium 保存后的截图: 在此处输入图片说明

Screenshot after cropping:裁剪后的截图:

在此处输入图片说明

I would check the value of 'location'. 我会检查'location'的值。 If your crop co-ordinates were outside of the image, then you would see black. 如果你的作物坐标在图像之外,那么你会看到黑色。 So for example - 所以例如 -

im = im.crop((-300, -300, -200, -200))

would give a black image. 会给出一个黑色的图像。

The reason may be the image was saved as a normalized version, which means the value of each pixel is in [0,1].原因可能是图像被保存为归一化版本,这意味着每个像素的值在 [0,1] 中。 Try multiply each pixel by 255 and view again.尝试将每个像素乘以 255 并再次查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM