可以直接进行对指定元素截图,本文章提供了另一种二次截图的方式。参考多篇文章,进行学习总结。
代码如下:
from selenium import webdriver
from time import sleep
from PIL import Image
from selenium.webdriver.common.by import By
class TestCase(object):
def __init__(self):
self.driver = webdriver.Chrome()
self.url = 'http://www.baidu.com'
#窗口必须最大化
self.driver.maximize_window()
self.driver.get(self.url)
def test_get_rect(self):
#点击设置
self.driver.find_element(By.XPATH,'//*[@id="s-usersetting-top"]').click()
sleep(1)
#点击搜索设置
self.driver.find_element(By.XPATH,'//*[@id="s-user-setting-menu"]/div/a[1]/span').click()
sleep(1)
more = self.driver.find_element(By.XPATH,'//*[@id="wrapper"]/div[6]')
sleep(1)
#保存整个网页截图
self.driver.get_screenshot_as_file("/Users/li/Desktop/截图1.png" )
#计算左上、右下,2个点的位置
left,upper=more.location['x'],more.location['y'] #左上
right,bottom=left+more.size['width'],upper+more.size['height'] #右下
#打开截图1.png
picture = Image.open("/Users/li/Desktop/截图1.png")
#处理截图1,对截图1进行二次截图。此处需要特别注意!!!windows不需要*2,mac需要
image_corp=picture.crop(box=(int(left)*2,int(upper)*2,int(right)*2,int(bottom)*2))
#保存截图2
image_corp.save('/Users/li/Desktop/截图2.png')
if __name__ == '__main__':
test = TestCase()
test.test_get_rect()
大致每个步骤都作了说明,这边比较坑的一个地方就是Mac在处理的时候,用2*2处理像素,所以需要*2,否则二次截图永远是歪的。。。。。。