How to save mobile screenshot using Headless Google Chrome with Selenium
Asked Answered
M

3

13
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')

Hello, The Image being taken by selenium is cut with page scroll (up/down & right/left) bars appearing, is there any way of taking screenshot of mobile view using selenium ?

EDIT:1

pastebin html test

for browser I adjust the width

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

for mobile

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

finally on both

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)
Math answered 26/6, 2020 at 10:57 Comment(11)
What's your environment info? This image is produced with no scroll bars in my environment (MacOS 10.15.5, selenium 3.141.0, chromedriver 83.0.4103.39)Norvell
I also cannot replicate the issue described on Chrome 83.0.4103.116 (x64; WinX); Selenium 3.141.0, Python 3.8.3. Please provide more details.Hon
Hi @Hon the bars are only a part of the issue, some websites have different views when opened in browser or mobile. however, when I open with this code I get the same result but cutMath
Could you provide some examples, what you get vs what you expect? The screenshot your code produces is the same as what I see when I visit the site on my iPhone.Hon
@Hon most of the examples are local HTML, but the issue is the same for any webiste that differs between mobile and browser (desktop)Math
What is the issue? What is happening VS what do you want to happen?Hon
@Hon how can I open a chat with youMath
Let us continue this discussion in chat.Math
@Hon check-update pleaseMath
I see the update but you still haven't described what the problem is, I can't help because you won't tell me what you need it to do, you just keep telling me what it does. @hadesfv if you can give more information as to what you expect from your bounty, that would be very helpful. I'm sure I can answer this but I have no clue what you want, only what you already have. It might be worth reading the How to create a Minimal, Reproducible Example guide.Hon
@Hon do you know that button on Chrome where you choose which mobile version and then you can browse normally as if you were on that mobile (in this example iPhone X), most websites display their content in different ways depending on which device is visiting. What I want is to take the screenshot as if that "button" is clicked and set to iPhone X ( I also adjust the height to take screenshot of fullpage)Math
K
0

If you want to take a full-screen screenshot of the webpage, you can use this.

The description of the problem you are experiencing isn't clear, so I'm assuming you want to hide the scroll bars and prevent them from appearing on the screenshot Selenium produces.

"""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)
Kruter answered 19/11, 2020 at 18:39 Comment(0)
S
0

That should work

from selenium import webdriver


def full_screenshot(driver, save_path):
    original_size = driver.get_window_size()
    required_width = driver.execute_script('return document.body.parentNode.scrollWidth')
    required_height = driver.execute_script('return document.body.parentNode.scrollHeight')
    driver.set_window_size(required_width, required_height)
    driver.save_screenshot(save_path)
    driver.set_window_size(original_size['width'], original_size['height'])


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.set_window_size(360, 640)  # Set the window size to match the mobile viewport dimensions
driver.get('https://stackoverflow.com/')

full_screenshot(driver, 'test.png')
driver.quit()

The full_screenshot function adjusts the window size to match the page's dimensions, takes a screenshot, and then restores the original window size. This should help you capture a screenshot of the entire page without scroll bars.

Siana answered 15/3, 2023 at 12:58 Comment(0)
A
0

check this answer

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

# Path to your chromedriver executable
chromedriver_path = '/path/to/chromedriver'

# Set up Chrome options
options = Options()
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--window-size=375,812")  # iPhone X dimensions

# Set up mobile emulation
mobile_emulation = {
    "deviceMetrics": {"width": 375, "height": 812, "pixelRatio": 3.0},
    "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1"
}
options.add_experimental_option("mobileEmulation", mobile_emulation)

# Create a WebDriver instance
driver = webdriver.Chrome(service=Service(chromedriver_path), options=options)

try:
    # Navigate to the desired webpage
    driver.get("https://www.example.com")

    # Take a screenshot
    screenshot_path = "mobile_screenshot.png"
    driver.save_screenshot(screenshot_path)
    print(f"Screenshot saved to {screenshot_path}")

finally:
    # Clean up and close the driver
    driver.quit()
Arnoldarnoldo answered 26/6 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.