selenium + chromedriver将网页抓取为图片

背景

公司老板要求对系统生成一个统计报表,统计项目非常的多。通过开发Web页面可以完美展示这些报表+图表。但是老板是使用手机查看,故需要将整个Web页面抓取为图片,通过邮件自动发送到老板邮箱。调研过程中遇到一下坑,现在梳理一下分析给大家

准备环境:

centos 7

python3.7 安装方式: https://www.cnblogs.com/s-seven/p/9105973.html

pip3 

chrome Linux  76版本, 安装文件:  https://pan.baidu.com/s/149msyjTIOq678hipzacYnQ  

安装命令: yum install -y google-chrome-stable-76.0.3809.100-1.x86_64.rpm

chromedriver ,这个driver的版本需要和上面chrome的版本对应,不然会报版本错误 下载地址:  https://pan.baidu.com/s/1ZrWvxR6Jyv5xPW92ep6fGA

安装命令: unzip chromedriver_linux64.zip && chromedriver /usr/bin/chromedriver

运行步骤:

1. 安装 selenium

 #pip3 install selenium

2. 创建python脚本,capture_html.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from selenium import webdriver
import io,sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110"')
options.add_argument('--window-size=1920,1080')
driver = webdriver.Chrome(chrome_options = options, executable_path=r'/usr/bin/chromedriver')
URL='http://192.168.1.138:8000/DataDashboard' #修改为自己的URL
try:
    driver.get(URL)
    driver.implicitly_wait(5)
    print(driver.title)
    S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
    driver.set_window_size(S('Width'),S('Height'))
    driver.find_element_by_tag_name('body').screenshot('web_screenshot.png')
finally:
    driver.quit()

3.执行脚本 , 生成的图片快照为 当前目录下web_screenshot.png

#python3 capture_html.py 

PS: 如果发现抓取出来的图片中文字显示为方框或者乱码,请根据以下文档安装字体。

https://www.aityp.com/centos7%E5%AE%89%E8%A3%85%E4%B8%AD%E6%96%87%E5%AE%8B%E4%BD%93-phantomjs/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值