2016-04-13 75 views
2

所以我使用硒/ phantomjs中最基本的方式來執行向下滾動操作。 它似乎在代碼中都很好,但不起作用。 我嘗試打印「document.body.scrollHeight」,每次滾動後它保持不變。 (例如高度保持在10532)phantomjs不會向下滾動使用window.scollTo

我瀏覽某個人喜歡「twitter.com/XXXXX」

的Twitter頁面的任何一個都可以給我什麼我可以做這裏的暗示?

我使用的webdriver的是phantomjs

下面的代碼:

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 
+0

有你檢查phantomjs是否有滾動?當然,無頭瀏覽器不滾動... – evolutionxbox

回答

3

我會等待滾動高度增加,使用document.documentElement.scrollHeight代替:

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;") 
+1

感謝您的幫助!我嘗試過這種方式,但沒有得到更好的結果,我試圖提高等待時間高達60秒,但仍然會增加超時例外。我看了截圖,一切正常,它正在尋找正確的頁面。它所要做的只是滾動,但它沒有。我相信我的網絡連接沒問題。非常奇怪的問題。 –

+0

它可以正常工作,但本例中的頁面不可滾動。我已經用更長的頁面更新了網址。 –