2
votes

So I was using the most basic way in selenium/phantomjs to do the scroll down action. It seems to be all good in code, but doesn't work. I try to print "document.body.scrollHeight", after every scroll it stays the same. (e.g. height stays at 10532)

I'm browsing twitter page of a certain person like "twitter.com/XXXXX"

Can Any one give me a hint on what can I do here?

The webdriver I'm using is phantomjs

Here's the code:

def getfullpage(url):
    print "getting fullpage..."
    driver.get(url)
    time.sleep(2)
    reloads = 3000
    pause = 0
    driver.save_screenshot("what'shappening.jpg")
    for times in range(reloads):
        driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
        time.sleep(pause)
        newheight = driver.execute_script("return document.body.scrollHeight")
        print newheight
    page = driver.page_source.encode("utf-8","ignore")
    return page
1
Have you checked if phantomjs even has a scroll? Surely a headless browser doesn't scroll... - evolutionxbox

1 Answers

3
votes

I would wait for the scroll height to increase and use the document.documentElement.scrollHeight instead:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.PhantomJS()
wait = WebDriverWait(driver, 20)

driver.get("https://twitter.com/barackobama")
time.sleep(1)

# scroll the height
height = driver.execute_script("var h=document.documentElement.scrollHeight; window.scrollTo(0, h); return h;")

# wait for the scroll height to increase
wait.until(lambda drv: drv.execute_script("return document.documentElement.scrollHeight;") > height)

# display the final scroll height
print driver.execute_script("return document.documentElement.scrollHeight;")