phantomjs是一款软件,需要重新安装。
参考:
https://blog.csdn.net/liyahui_3163/article/details/79064108
案例代码:
from selenium import webdriver
import time
from PIL import Image
driver = webdriver.PhantomJS(r"D:\zzl\biancheng\phantomjs-2.1.1-windows\bin\phantomjs.exe")
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()
延伸:
phantomjs出bug的解决方法:(截图找bug)
driver = webdriver.PhantomJS()
driver.set_window_size(1920,1080)
try:
driver.get('http://whatsmyuseragent.com/')
except Exception,e:
driver.save_screenshot('screenshot.png')
driver.close()