python-3.x - Selenium webdriver python 元素屏幕截图无法正常工作

标签 python-3.x selenium selenium-webdriver firefox

我查阅了 Selenium python 文档,它允许截取元素的屏幕截图。我尝试了以下代码,它适用于小页面(打印时大约 3-4 个实际 A4 页):

from selenium.webdriver import FirefoxOptions

firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

# Configure options for Firefox webdriver
options = FirefoxOptions()
options.add_argument('--headless')

# Initialise Firefox webdriver
driver = webdriver.Firefox(firefox_profile=firefox_profile, options=options)
driver.maximize_window()

driver.get(url)
driver.find_element_by_tag_name("body").screenshot("career.png")

driver.close()

当我尝试使用 url="https://waitbutwhy.com/2020/03/my-morning.html" 时,它按预期提供了整个页面的屏幕截图。但是当我用 url="https://waitbutwhy.com/2018/04/picking-career.html" 尝试时,几乎一半的页面没有在屏幕截图中呈现(图像是太大而无法在此处上传),即使“body”标签确实在原始 HTML 中一直向下延伸。

我尝试过同时使用隐式和显式等待(设置为 10 秒,这足以让浏览器加载所有内容,包括评论和讨论部分),但这并没有提高屏幕截图的能力。为了确保 selenium 实际上正确加载网页,我尝试在没有 headless 标志的情况下加载,一旦网页完全加载,我运行 driver.find_element_by_tag_name("body").screenshot("career.png").屏幕截图又是半空白的。

screenshot 方法似乎有一些内存限制(虽然我找不到),或者 screenshot 方法本身背后的逻辑是有缺陷的。不过我想不通。我只是想截取整个“body”元素的屏幕截图(最好是在 headless 环境中)。

最佳答案

您可以尝试此代码,只是您需要使用命令从命令提示符安装包 pip install Selenium-Screenshot

import time
from selenium import webdriver
from Screenshot import Screenshot_Clipping


driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get("https://waitbutwhy.com/2020/03/my-morning.html")
obj=Screenshot_Clipping.Screenshot()
img_loc=obj.full_Screenshot(driver, save_path=r'.', image_name='capture.png')
print(img_loc)

time.sleep(5)
driver.close()

Outcome/结果出来就好了,你只需要缩放保存的截图

capture.png

希望这对你有用!

关于python-3.x - Selenium webdriver python 元素屏幕截图无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63857412/

相关文章:

python - 如何将长 WhatsApp 消息作为单条消息而不是多条消息发送

selenium - 测试按钮同时在浏览器的不同选项卡中单击

selenium-webdriver - 无法创建新的远程 session

Python随机数生成对于相同的种子是不同的

python - 不在网络抓取中迭代列表

javascript - 使用 Dropzone.js 上传 NIghtwatch.js 文件

selenium-webdriver - 如何在 Protractor 中获取页面的来源

selenium - webdriverIO 和 iOS 模拟器浏览器测试

python - 找不到文件错误 : [WinError 2] The system cannot find the file specified:

python-3.x - 来自 DataFrame 的一张图上的多个图