from selenium import webdriver import time from PIL import Image driver = webdriver.Chrome() driver.get('https://www.baidu.com/') time.sleep(3) # 演示一:全網頁截圖 # driver.save_screenshot('screenshot.png') # driver.quit() # 演示二:定位區塊截圖 driver.save_screenshot(r'photo.png') # 一次截圖:形成全圖 baidu = driver.find_element_by_id('su') # 截圖按鈕百度一下 # baidu = driver.find_element_by_xpath("//div[@id='lg']/img[@class='index-logo-src']") #截圖百度logo圖片 # print(baidu) left = baidu.location['x'] # 區塊截圖左上角在網頁中的x坐標 top = baidu.location['y'] # 區塊截圖左上角在網頁中的y坐標 right = left + baidu.size['width'] # 區塊截圖右下角在網頁中的x坐標 bottom = top + baidu.size['height'] # 區塊截圖右下角在網頁中的y坐標 # print({"left": left, "top": top, "right": right, "bottom ": bottom}) # print("baidu.size['width']:%s" % baidu.size['width']) # print("baidu.size['height']:%s" % baidu.size['height']) picture = Image.open(r'photo.png') picture = picture.crop((left, top, right, bottom)) # 二次截圖:形成區塊截圖 picture.save(r'photo2.png') driver.quit()