1

I want to take screenshot from site in difference size(mobile,desktop) without horizontal scroll. i used the blew code,but in mobile size there is scroll

from selenium import webdriver

import time

links = ['digikala.com']
# driver = webdriver.Chrome("/home/arezoo/Desktop/chromedriver")
with webdriver.Chrome("/home/arezoo/Desktop/chromedriver") as driver:
    for link in links:
        desktop = {'output': str(link) + '-desktop.png',
                   'width': 2200,
                   'height': 1800}
        tablet = {'output': str(link) + '-tablet.png',
                  'width': 1200,
                  'height': 1400}
        mobile = {'output': str(link) + '-mobile.png',
                  'width': 680,
                  'height': 1200}
        linkWithProtocol = 'http://' + str(link)
        # set the window size for desktop
        driver.set_window_size(desktop['width'], desktop['height'])
        driver.get(linkWithProtocol)
        # time.sleep(s)
        driver.save_screenshot(desktop['output'])

        # set the window size for tablet
        driver.set_window_size(tablet['width'], tablet['height'])
        driver.get(linkWithProtocol)
        time.sleep(2)
        driver.save_screenshot(tablet['output'])

        # set the window size for mobile
        driver.set_window_size(mobile['width'], mobile['height'])
        driver.get(linkWithProtocol)
        time.sleep(2)
        driver.save_screenshot(mobile['output'])

arezoo
  • 328
  • 3
  • 14

1 Answers1

1

The way you're taking screenshots is correct already. Selenium will just control your browsers window size when calling your website. If you try it with Chrome an a Windows machine, you will also see a vertical scrollbar when you use a narrow window. This will just not occur when using mobile emulation or a "real" mobile device.

Therefore, you have two options:

  1. Improve your website itself so the content will be delivered according to the browsers width in any case.
  2. Tell your webdriver to act like a mobile device (hence telling your website that it is one, forcing mobile mode).

While the first possibility IMO is the better, yet harder to achieve one, the second version can be easier. I do not know how your site determines whether to use mobile mode or not, but I guess, it reads the header from the browser. You could try adding a modified User Agent header to your requests (see here for example). Or, even more sophisticated, use the mobile emulation of your webdriver. Notes and examples - also in python - can be found here:

https://chromedriver.chromium.org/mobile-emulation

ahuemmer
  • 1,653
  • 9
  • 22
  • 29