100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 使用selenium网页截图 解决截图不全问题

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

时间:2021-11-15 21:11:57

相关推荐

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

#!/usr/bin/python3# -*- coding:utf-8 -*-import timefrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom PIL import Imagedef 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(executable_path=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 = 1height = 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 += 1else:breaktime.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转pdfimage1 = 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("")

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。