python - 使用 Selenium Python 和 Chrome 驱动程序截取完整网页的屏幕截图
问题描述
我想截取一个网站的整个页面。以下是网站条件
- 它需要使用登录表单进行身份验证
- 我要截图的网站是用Javascript渲染的(动态渲染),不是静态渲染的(
body
标签里面只是script
标签)
我确实尝试了一些我能找到的解决方案,但它们都没有按我的意愿工作。以下是我尝试过的一些尝试
- 链接这个需要使用 headless chrome,这让我无法填写登录表格
- 当我尝试删除无头选项时,我收到此错误,
"message":"Cannot take screenshot with 0 height."
我猜这是因为内容是由 Javascript 呈现的。请注意,我已经给它一些时间来渲染time.sleep(5)
- 当我尝试选择另一个元素时,结果会有所不同。有些给出与上面相同的错误消息,有些给我截图但不是整页,只是可见部分(与 using 相同的结果
browser.save_screenshot()
)。下面是我试过的代码。
def S(X): return browser.execute_script(
'return document.querySelector("#main-layout-content").scroll'+X
)
browser = webdriver.Chrome()
browser.get('some link go here')
browser.set_window_size(S('Width') + 100, S('Height') + 1000)
#The print statement below work
print(S('Height'))
browser.find_element_by_id('main-layout-content').screenshot('web_screenshot.png')
有什么办法可以达到我的需要吗?
解决方案
这是我为获取网页的全尺寸屏幕截图所做的
from selenium import webdriver
browser = webdriver.Chrome()
# We go to the webpage here and wait 2 seconds for fully load
browser.get('https://someURL')
time.sleep(2)
# Where to save the picture
directory = '/home'
# Video title
title = 'Hello world'
try:
# We try to get the top-level component in which all out page is its children
# This is different for each website
elem = browser.find_element_by_id('main-layout-content')
# Get the height of the element, and adding some height just to be sage
total_height = elem.size['height'] + 1000
# Set the window size - what is the size of our screenshot
# The width is hardcoded because the screensize is fixed for each computer
browser.set_window_size(1920, total_height)
# Wait for 2 seconds
time.sleep(2)
# Take the screenshot
browser.find_element_by_id(
'main-layout-content').screenshot(f'./{directory}/{title}.png')
except SystemError as err:
print('Take screenshot error at' + title)
推荐阅读
- javascript - 使用 refs 从父级调用子挂钩函数
- python - 如何在 Python 的 for 语句中使用 if
- osgi - 跟踪整个 repo 中节点上的移动操作
- scala - Spark Checkpoint 分区无法转换为 CoGroup 分区
- python - PyQt5 错误:此应用程序无法启动,因为它无法找到或加载 Qt 平台插件“xcb”
- c++ - 在地图中使用步幅
- r - 删除列中的某些值(包含特定字符)
- jenkins - Jenkins 作业通过后,工作节点上的进程不会被杀死
- javascript - 我应该使用 mixins 还是实用程序类?
- python-3.x - 我如何使用户输入的任何其他内容都会收到错误消息,除了我的命令