gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:01:45 25 4
gpt4 key购买 nike

我一直在做研究,到目前为止我找到了我计划使用它的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com