利用Python对网页渲染效果保存为图片

      发布在:Python技术      评论:0 条评论

具体代码如下

from selenium import webdriver
import time

def get_full_page_height(driver):
# 执行 JavaScript 获取文档的完整高度
scroll_height = driver.execute_script('return Math.max('
'document.body.scrollHeight, '
'document.body.parentNode.scrollHeight, '
'document.body.offsetHeight, '
'document.documentElement.clientHeight, '
'document.documentElement.scrollHeight, '
'document.documentElement.offsetHeight);')
return scroll_height
def capture_full_page_screenshot(url, save_path):
# 启动Chrome浏览器
options = webdriver.ChromeOptions()
options.add_argument('--headless') # 无头模式,不显示浏览器窗口
driver = webdriver.Chrome(options=options)

try:
# 默认打开网页浏览器大小
driver.set_window_size(1920,1080)
driver.get(url)

# 等待页面完全加载,这里设置等待时间为10秒
time.sleep(10) # 可以根据实际情况调整等待时间



# 获取文档完整渲染后的高度
full_height = get_full_page_height(driver)
print('full_height=%s' % full_height)
if full_height<1080:
full_height = 1080
print('full_height=%s' % full_height)
# 设置浏览器窗口大小为整个页面高度 留出15px 重新设置是为了可以截取整个页面
driver.set_window_size(1920, full_height+15)

# 截取整个页面的效果图
driver.save_screenshot(save_path)
print(f"页面截图已保存至: {save_path}")

except Exception as e:
print(f"截图过程中发生错误: {e}")

finally:
# 关闭浏览器
driver.quit()

# 要截取的网页地址
url = r"http://www.80zx.com/" # 请将路径替换为你本地index.html文件的路径


# 保存截图的路径及文件名
save_path = "screenshot.png" # 截图保存的文件名及路径

# 调用截取页面截图函数
capture_full_page_screenshot(url, save_path)


相关文章
热门推荐