Win10下用selenium、Image.crop() 截圖時、座標不許確的問題

截百度按鈕的圖




先將整個窗口的圖保存下來

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
element = driver.find_element_by_xpath('//input[@id="su"]')
# 座標
print(element.location)
# 大小
print(element.size)
#    把當前窗口截圖保存
driver.get_screenshot_as_file('1.png')




正常狀況下,直接根據圖片的座標和大小,將對應參數給到crop()

from PIL import Image

image = Image.open('1.png')
x = 738
y = 220
im = image.crop((x, y, x + 100, y + 36))
im.show()



結果倒是這樣?



看這內容,只截到「度」字,距離目標還有這麼長一截




緣由是本身電腦縮放與佈局(桌面右鍵、顯示設置)用的125%爲推薦設置



把這個設置調回100%便可準確截圖

或者在給crop()參數的時候,所有乘以對應的比列也能準確截圖

from PIL import Image

image = Image.open('1.png')
x = 738 * 1.25
y = 220 * 1.25
im = image.crop((x, y, x + 100 * 1.25, y + 36 * 1.25))
im.show()

相關文章
相關標籤/搜索