2012-09-20 96 views
25

我写了很多刮板,但我不知道如何处理无限滚动。这些天大部分网站等,Facebook,Pinterest有无限的滚动。scle网站无限滚动

+2

这里最好的选择就是使用这些网站的API--到目前为止,这将是最简单和最可靠的选择。除此之外,你将不得不处理JavaScript,这基本上意味着运行一个完整的浏览器 - 这样的库确实存在。 –

+0

听起来像一个模拟,你可以指向一些处理jscript的例子 –

回答

24

你可以使用硒来取消像twitter或facebook这样的无限滚动网站。

步骤1:使用PIP

pip install selenium 

步骤2安装硒:使用下面的代码来自动无限滚动和提取源代码

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.common.exceptions import NoSuchElementException 
from selenium.common.exceptions import NoAlertPresentException 
import sys 

import unittest, time, re 

class Sel(unittest.TestCase): 
    def setUp(self): 
     self.driver = webdriver.Firefox() 
     self.driver.implicitly_wait(30) 
     self.base_url = "https://twitter.com" 
     self.verificationErrors = [] 
     self.accept_next_alert = True 
    def test_sel(self): 
     driver = self.driver 
     delay = 3 
     driver.get(self.base_url + "https://stackoverflow.com/search?q=stckoverflow&src=typd") 
     driver.find_element_by_link_text("All").click() 
     for i in range(1,100): 
      self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") 
      time.sleep(4) 
     html_source = driver.page_source 
     data = html_source.encode('utf-8') 


if __name__ == "__main__": 
    unittest.main() 

步骤3:如果需要,打印这些数据。

+0

循环是否意味着我们向下滚动100次?其中100是随机选择的数字。是对的吗? –

+0

@satarupa你是对的循环向下滚动100次 –

20

大多数无限滚动的网站(如Lattyware笔记)也具有适当的API,并且您可能会更好地使用这种方式,而不是通过抓取。

但是如果你必须凑...

这类网站都使用JavaScript,当您到达页面的底部,要求从网站的附加内容。所有你需要做的是找出额外的内容的URL,你可以检索它。找出所需的URL可以通过检查脚本,使用Firefox Web控制台或使用debug proxy来完成。

例如,打开Firefox Web控制台,关闭除Net之外的所有过滤器按钮,然后加载要擦除的站点。您将在加载时看到所有文件。在浏览Web控制台的同时滚动页面,您将看到用于其他请求的URL。然后你可以自己请求这个URL,看看数据是什么格式(可能是JSON),然后把它放到你的Python脚本中。

+0

你能举一个具体的例子来说明如何去做吗? – tatsuhirosatou

+0

我已经添加了一些更多的细节,希望它有帮助! – kindall

1

找到ajax源代码的网址将是最好的选择,但对某些网站来说可能很麻烦。或者,您可以使用QWebKit之类的无头浏览器从PyQt发送键盘事件,同时从DOM树中读取数据。 QWebKit有一个不错的和简单的API。