使用selenium网页截图,解决截图不全问题

#!/usr/bin/python3
# -*- coding:utf-8 -*-


import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from PIL import Image


def screenshot_to_pdf_and_png(link):
    ''' 参数:网址
        功能: 保存网址截图
             解决了截图不全问题
             解决了懒加载问题
             保存俩种图片格式
    '''
    path = './'
    # 1> 获取chrome参数对象
    chrome_options = Options()
    # 2> 添加无头参数r,一定要使用无头模式,不然截不了全页面,只能截到你电脑的高度
    chrome_options.add_argument('--headless')
    # 3> 为了解决一些莫名其妙的问题关闭 GPU 计算
    chrome_options.add_argument('--disable-gpu')
    # 4> 为了解决一些莫名其妙的问题浏览器不动
    chrome_options.add_argument('--no-sandbox')
    # 5> 添加驱动地址。 由于在函数内,设置参数chrome_options需要再导入
    driver = webdriver.Chrome(service=r'D:\银联工作\test\chromedriver.exe' ,chrome_options=chrome_options)
    # 6> 模仿手动滑动滚动条,解决懒加载问题
    try:
        driver.implicitly_wait(20)
        driver.get(link)

        # 模拟人滚动滚动条,处理图片懒加载问题
        js_height = "return document.body.clientHeight"
        driver.get(link)
        k = 1
        height = driver.execute_script(js_height)
        while True:
            if k * 500 < height:
                js_move = "window.scrollTo(0,{})".format(k * 500)
                print(js_move)
                driver.execute_script(js_move)
                time.sleep(0.2)
                height = driver.execute_script(js_height)
                k += 1
            else:
                break

        time.sleep(1)

        # 7>  # 直接截图截不全,调取最大网页截图
        width = driver.execute_script(
            "return Math.max(document.body.scrollWidth, document.body.offsetWidth, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth);")
        height = driver.execute_script(
            "return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);")
        print(width, height)
        # 将浏览器的宽高设置成刚刚获取的宽高
        driver.set_window_size(width + 100, height + 100)
        time.sleep(1)
        png_path = path + '/{}.png'.format('xx网址截图')

        # 截图并关掉浏览器
        driver.save_screenshot(png_path)
        driver.close()
        # png转pdf
        image1 = Image.open(png_path)
        im1 = image1.convert('RGB')
        pdf_path = png_path.replace('.png', '.pdf')
        im1.save(pdf_path)

    except Exception as e:
        print(e)


if __name__ == '__main__':
    screenshot_to_pdf_and_png("http://www.douban.com")

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值