繁体   English   中英

如何使用带有 Selenium 的 Headless Google Chrome 保存手机屏幕截图

[英]How to save mobile screenshot using Headless Google Chrome with Selenium

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
mobile_emulation = {
                "deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0},
                "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1"}
options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(options=options)
driver.get('https://stackoverflow.com/')
driver.save_screenshot('test.png')

您好,selenium 拍摄的图像被剪切并出现页面滚动(上/下和右/左)条,有没有什么方法可以使用 selenium 截取移动视图?

编辑:1

pastebin html 测试

对于浏览器我调整宽度

required_width = driver_selected.execute_script('return document.body.parentNode.scrollWidth')

用于手机

required_width = driver_selected.get_window_size().get('width') # Keep same

最后在两者上

required_height = driver_selected.execute_script('return document.body.parentNode.scrollHeight')
driver_selected.set_window_size(required_width, required_height)
driver_selected.find_element_by_tag_name('body').screenshot(png_file)

如果你想对网页进行全屏截图,你可以使用这个。

您遇到的问题的描述不清楚,所以我假设您想隐藏滚动条并防止它们出现在 Selenium 生成的屏幕截图上。

"""Take a full-page screenshot of the browser"""

# Save the original window size so we can restore it later
original = self.driver.get_window_size()
# Format the original in a tuple object we can use later
original = (original['width'], original['height'],)

# Get the height that's needed in order to fully render the page
newheight = int(self.driver.execute_script("""
return Math.max(
    document.body.scrollHeight,
    document.body.offsetHeight,
    document.documentElement.clientHeight,
    document.documentElement.scrollHeight,
    document.documentElement.offsetHeight
);
"""))

# Set the new height
# Most responsive webpages handle width flawlessly, so you can use a constant width
# You can also set it dynamically if you wish
self.driver.set_window_size(1000, newheight)

# Hide the main scrollbar using some css tricks
# You can also inject a
# <style>* {overflow: hidden}</style>
# to hide all scrollbars if you want 
self.driver.execute_script("""
document.body.parentElement.style.overflow = "hidden";
""")

# b64ss = self.driver.get_screenshot_as_base64()
# print(b64ss)
# The screenshot must be saved to a file because base64 has
# size restrictions that usually cause an incomplete screenshot

self.driver.save_screenshot('mobile_fullpage_screenshot.png')

# Restore the original window sizes
self.driver.set_window_size(*original)

暂无
暂无

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

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