python - 使用 python 抓取具有无限滚动的网站

标签 python selenium web-crawler scrapy

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

最佳答案

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

第 1 步:使用 pip 安装 Selenium

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 + "/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()

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

第 3 步:根据需要打印数据。

关于python - 使用 python 抓取具有无限滚动的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22702277/

相关文章:

python - Keras:训练期间和纪元结束时的不同验证 AUROC

python - scrapy如何正确使用Rules、restrict_xpaths抓取解析URL?

基于Scrapy的Python函数对整个网站进行爬取

python - Scrapy 忽略 noindex

python - 如何限制 matplotlib 图的边框大小?

python - pytest-cov - 不要计算集成测试目录的覆盖率

python - im.getcolors() 返回 None

java - 如何在 IE 中使用 selenium 记录测试用例

selenium - 尝试将鼠标悬停在菜单上并单击子菜单中的链接,但没有成功

javascript - protractorjs 中的 browser.wait 调用过多