使用python无限滚动的爬网站点

add*_*ons 8 python selenium web-crawler scrapy

我一直在做研究,到目前为止我发现了我将计划使用它的scrapy的 python 包,现在我试图找出使用scrapy构建爬虫以无限滚动来爬取站点的好方法。在挖掘之后我发现有一个包调用 selenium 并且它有 python 模块。我有一种感觉,有人已经使用 Scrapy 和Selenium通过无限滚动来抓取站点。如果有人能指出一个例子,那就太好了。

小智 8

这是对我有用的简短代码:

SCROLL_PAUSE_TIME = 20

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

posts = driver.find_elements_by_class_name("post-text")

for block in posts:
    print(block.text)
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以使用 selenium 废弃无限滚动的网站,例如 twitter 或 facebook。

第 1 步:使用 pip 安装 Selenium

pip install selenium 
Run Code Online (Sandbox Code Playgroud)

第 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 + "/search?q=stackoverflow&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()
Run Code Online (Sandbox Code Playgroud)

for 循环允许您解析无限滚动并发布您可以提取加载的数据。

第 3 步:如果需要,打印数据。


max*_*ywb 5

from selenium.webdriver.common.keys import Keys
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.something.com")
lastElement = driver.find_elements_by_id("someId")[-1]
lastElement.send_keys(Keys.NULL)
Run Code Online (Sandbox Code Playgroud)

这将打开一个页面,找到给定的最底部元素id并将该元素滚动到视图中。随着页面加载更多,您将不得不继续查询驱动程序以获取最后一个元素,并且我发现随着页面变大,这非常慢。时间由调用支配,driver.find_element_*因为我不知道显式查询页面中最后一个元素的方法。

通过实验,您可能会发现页面动态加载的元素数量存在上限,最好编写一些加载该数字的内容,然后才调用driver.find_element_*.