一、頁面截圖
selenium中頁面截圖的方法比較簡單,可以直接使用selenium自帶的截圖方式save_screenshot(‘filename’)。
from selenium import webdriver driver = webdriver.Chrome() driver.get("http://xlrz.chdi.com.cn/wssq/")
driver.save_screenshot("login.png")
注意:save_screenshot的文件后綴名只能是png。
get_screenshot_as_flie("文件路徑"),與save_screenshot(‘filename’)功能相似。不過get_screenshot_as_flie("文件路徑")可以指定文件路徑,而save_screenshot(‘filename’)是默認在項目目錄下生成圖片。
二、元素截圖
元素截圖需要先安裝第三方pillow庫,安裝命令是“pip install pillow”.代碼中需要先導入Image模組。
例如獲取學歷認證登錄頁面,【登錄】按鈕具體代碼如下:
from selenium import webdriver from PIL import Image driver = webdriver.Chrome() driver.get("http://xlrz.chdi.com.cn/wssq/") #獲取登錄頁面的截圖 driver.save_screenshot('login.png') #定位登錄按鈕 imgcode=driver.find_element_by_name("submit") #loaction方法獲取元素坐標值X,y,且以字典的方式返回 left=imgcode.location['x'] top=imgcode.location['y'] #size方法獲取元素的高度和寬度,以字典方式返回 right=left+imgcode.size['width'] bottom=top+imgcode.size['height'] #打開登錄頁面的截圖 im=Image.open("login.png") #獲取登錄按鈕截圖 mg=im.crop((left,top,right,bottom)) #保存截圖,命名未ann mg.save('ann.png')