使用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")

win7哪个系统最好用
怎么使用手机远程访问电脑文件?(3种方法)