Typecho Wiki
每一个作品都值得被记录

Linux命令行界面使用Python+Selenium+Chrome对网页截图教程

Typecho维基君资源分享 • 1194次浏览 • 发布 2022-07-14 • 更新 2022-07-14
极致加速的V2Ray 助您畅享全球网络 & 搬瓦工VPS最新优惠码
🛜自用大流量超低月租手机卡推荐榜单 #拒绝流量焦虑

linux命令行界面使用Python+Selenium+Chrome对网页截图保存(js渲染后的页面)

程序版本:
系统:centos7
python:3.6
Selenium:3.141
chrome|chromedriver:88.0.4324.96
chrome版本下载:Linux Google Chrome
chromedriver版本下载:chromedriver

程序安装:

# python3安装略过

# Selenium安装
pip3 install Selenium

# 安装chrome
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install google-chrome-stable_current_x86_64.rpm -y

# 下载chromedriver(先确认安装的chrome版本,再下载对应的chromedriver版本)
#查看版本
[root@localhost ~]#rpm -qa|grep google-chrome
google-chrome-stable-88.0.4324.96-1.x86_64

#下载对应版本chromedriver
wget http://chromedriver.storage.googleapis.com/88.0.4324.96/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
mv chromedriver /usr/local/bin/

python代码:

#!/bin/env python3from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import timeoptions=webdriver.ChromeOptions()# 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
options.add_argument('--headless')# 谷歌文档提到需要加上这个属性来规避bug
options.add_argument('--disable-gpu')# 取消沙盒模式
options.add_argument('--no-sandbox')options.add_argument('--disable-dev-shm-usage')# 指定浏览器分辨率
options.add_argument('window-size=1920x1080')driver=webdriver.Chrome(options=options)#网页地址
driver.get('https://www.baidu.com')
#等待2秒再截图,如果网页渲染的慢截图的内容会有问题
#time.sleep(2)#截图
driver.get_screenshot_as_file('/tmp/baidu.png')#退出
driver.close()

执行脚本截图的图片乱码:

Linux命令行界面使用Python+Selenium+Chrome对网页截图教程

# 解决文字乱码
把windows系统下微软雅黑字体拷贝到linux系统下
# windows字体目录
C:WindowsFonts微软雅黑<span>MSYH.TTC
# linux字体目录
/usr/share/fonts

再次查看网页截图图片:

Linux命令行界面使用Python+Selenium+Chrome对网页截图教程

广告声明:文内含有的对外跳转链接(包括不限于超链接、二维码、口令等形式),用于传递更多信息,节省甄选时间,结果仅供参考,Typecho.Wiki所有文章均包含本声明。
厂商投放

【腾讯云】🎉五一云上盛惠!云服务器99元/月续费同价!

腾讯云五一劳动节海量产品 · 轻松上云!云服务器首年1.8折起,买1年送3个月!超值优惠,性能稳定,让您的云端之旅更加畅享。快来腾讯云选购吧!

广告
添加新评论 »