Search code examples
pythonseleniumscreenshot

Selenium - Scroll for screenshots


I have a python script that goes through the UI and fills out a lot of pages. I take a screenshot, but if the page is longer than the screen, then I miss half of the page. I tried a longer length, but with the normal pages, it's ridiculous and unusable. I tried to use ashot, but can't figure out how to add it to my project in pycharm.

Any wisdom or other ideas? Thanks.

UPDATE on things tried that didn't work (nothing happened on the page:

actions = ActionChains(driver)
actions.move_to_element(continuebtn)

Also:

chrome_options.add_argument('--enable-javascript')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.execute_script("window.scrollTo(0, 1080);")

Solution

  • You could take a multiple screenshots and scroll through the whole page.

    A simple example would be:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as ec
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.firefox.options import Options
    import time
    
    d = webdriver.Firefox(executable_path="PATH TO YOUR DRIVER")
    d.get("https://en.wikipedia.org/wiki/HTTP_cookie")
    time.sleep(1)
    scrollHeight = d.execute_script("return window.scrollMaxY")
    index = 0
    while d.execute_script("return window.pageYOffset") < scrollHeight:
        d.save_screenshot(PICTURE_PATH+"/"+ FILENAME + str(index).zfill(2) + ".png")
        d.execute_script("window.scrollByPages(1)")
        # maybe call time.sleep in here somewhere to load lazyloaded images
        time.sleep(0.2)
        index += 1
    d.quit()