Typecho主题插件站
每一个作品都值得被记录

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

Typecho爱好者资源分享 • 1104次浏览 • 发布 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()

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

baidu.png

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

再次查看网页截图图片:

baidu (2).png

厂商投放
添加新评论 »