文章目录
1. 前置条件
- win10, python 3.6
- 下载PhantomJS, 下载地址
- 下载解压完成后, 放入一个你喜欢的目录(意思就是放哪儿都行), 但要记得你放哪儿了, 一会儿要用
- 我的就放这儿了
2. 上脚本
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : screen_shot.py
@Time : 2020/01/01 09:28:03
@Author : zhugelaoliu
@Version : 1.0
@Desc : 网页截图
'''
import os
from selenium import webdriver
# 此处 selenium==2.48.0 版本的, 最新版本不支持PhantomJS
import arrow
from PIL import Image
class ScreenShot():
def __init__(self, url, picname, **kwargs):
self.url = url
self.picname = picname + '.png'
self.base_dir = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
# 前置条件中提到的要用到的PhantomJS地址
self.driver = webdriver.PhantomJS(
executable_path=r'D:/Anaconda3/envs/py36/Scripts/phantomjs-2.1.1-windows/bin/phantomjs.exe')
# 以下为另一种解决方案(未使用)
# self.chrome_options = webdriver.ChromeOptions()
# self.chrome_options.add_argument("--headless")
# self.chrome_options.add_argument('--disable-gpu')
# self.driver = webdriver.Chrome(chrome_options=self.chrome_options,
# executable_path=r'D:/Anaconda3/envs/py36/Scripts/chromedriver_win32/chromedriver.exe')
# end
self.now = arrow.now('local')
self.month = self.now.format('YYYYMM')
self.today = self.now.format('YYYYMMDD')
self.new_picname = '_'.join([self.today, self.picname])
self.screen_shot_dir = os.path.join(
self.base_dir, f'report_images/{self.month}/{self.today}')
if not os.path.exists(self.screen_shot_dir):
os.makedirs(self.screen_shot_dir)
self.screen_shot_image = os.path.join(
self.screen_shot_dir, self.new_picname)
@property
def getImage(self):
'''
截取全屏,并保存在images文件夹
:return: 无
'''
self.driver.get(self.url)
self.driver.maximize_window()
self.driver.save_screenshot(self.screen_shot_image)
self.driver.close()
return self.screen_shot_image
def getElementImage(self, element):
"""
截图,指定元素图片
:param element: 元素对象
:return: 无
"""
print(f'正在打开 {self.url} ---> ', end='')
self.driver.get(self.url)
self.driver.maximize_window()
element_obj = self.driver.find_element_by_class_name(element)
# 备用的查找元素方式
# element_obj = self.driver.find_element_by_id(element)
print(f'ok, 正在截屏 ---> ', end='')
self.driver.save_screenshot(self.screen_shot_image)
left = element_obj.location['x']
top = element_obj.location['y']
elementWidth = left + element_obj.size['width']
elementHeight = top + element_obj.size['height']
picture = Image.open(self.screen_shot_image)
picture = picture.crop((left, top, elementWidth, elementHeight))
picture.save(self.screen_shot_image)
self.driver.close()
print(f'Done',)
return self.screen_shot_image
def main():
url = 'https://www.csdn.net/'
picname = 'csdn'
obj = ScreenShot(url, picname)
image = obj.getElementImage('clearfix')
if __name__ == "__main__":
main()
3. 上结果