先列一下使用的软件版本
Python 3.7.2
selenium 4.2.0
Google Chrome 102.0.5005.61
chrome-driver:102.0.5005.61/chromedriver_linux64.zip
一、python3 安装 升级pip3
二、安装最新版的selenium
yum install selenium
三、安装google-chrome
自动下载google-chrome: curl https://intoli.com/install-google-chrome.sh | bash
#查看google-chrome的版本
[root@localhost work]$ google-chrome --version
Google Chrome 102.0.5005.61
四、安装 chrome-driver
根据第三步google的版本从下面的网址下载对应版本chrome-driver
http://chromedriver.storage.googleapis.com/index.html
#解压文件
unzip chromedriver_linux64.zip
#将chromedriver 放到 /usr/bin/
mv chromedriver /usr/bin/
#给chromedriver执行权限
chmod +x /usr/bin/chromedriver
四、执行代码
'''
Author: zhangxuepeng
Date: 2022-06-1
Description: 网页截屏
'''
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time
import os
# chrome-driver 安装路径
DRIVER_PATH = r'/usr/bin/chromedriver'
# 若是windows环境下
# DRIVER_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver'
img_path = r'/root/work' # 存放截图的位置
if __name__ == "__main__":
# 浏览器基础配置
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless') # 无头参数
options.add_argument('--disable-gpu') # 禁用gpu 防止占用资源出现bug
options.add_argument('window-size=1920x1080') # 设置分窗口辨率
options.add_argument('--start-maximized') # 最大化运行(全屏窗口),不设置,取元素可能会报错
options.add_argument('--hide-scrollbars')
options.binary_location = r'/usr/bin/google-chrome'
s = Service(DRIVER_PATH)
# 启动浏览器
driver = Chrome(service=s, options=options)
try:
# 访问页面
driver.get('https://www.baidu.com')
time.sleep(10) # 延迟10s截图
# 截屏
img_name = time.strftime(
'%Y-%m-%d', time.localtime(time.time())) # 截屏名称 时间表示
img = "%s.png" % os.path.join(img_path, img_name) # 图片
driver.get_screenshot_as_file(img) # 保存截图
except Exception as e:
print(e)
driver.close() # 关闭浏览器
driver.quit()
五、运行文件
python3 cut.py
就会生成截图,大家拿去玩儿吧
linux 下要用 options.add_argument('--headless') # 无头参数 进行隐示访问才可
有问题大家百度哦~