繁体   English   中英

Selenium webdriver python 元素屏幕截图无法正常工作

[英]Selenium webdriver python element screenshot not working properly

我查阅了 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()

结果/结果就像,你只需要放大保存的屏幕截图

捕获.png

希望这对你有用!

Selenium-Screenshot 2.0 没有 Screenshot_Clipping 模块。 上面需要的更改在: https ://pypi.org/project/Selenium-Screenshot/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM