使用scrapy+splash+Lua脚本实现滚轮动态加载爬取CSDN

爬取CSDN的时候发现,csdn需要一直使用鼠标滑轮下拉,动态加载

使用Lua脚本,详细解释见官方文档https://splash.readthedocs.io/en/stable/

function main(splash, args)
  splash:go(args.url)
  local scroll_to = splash:jsfunc("window.scrollTo")
  scroll_to(0, 300)
  splash:set_viewport_full()
  return {png=splash:png()}
end

发现可以获取到滑动以后的内容

接下来就是如何将该脚本结合到scrapy中,工具使用的是pycharm

class CSDNSpider(scrapy.Spider):

    name = 'test'
    def start_requests(self):

        # script = """
        #             function main(splash,args)
        #                 splash:set_viewport_size(1028, 10000)
        #                 splash:go(args.url)
        #                 local scroll_to = splash:jsfunc("window.scrollTo")
        #                 scroll_to(0, 2500)
        #                 splash:wait(5)
        #                 return {
        #                     html = splash:html()
        #                 }
        #             end
        #             """
        script = """
                function main(splash, args)
                  splash:go(args.url)
                  local scroll_to = splash:jsfunc("window.scrollTo")
                  scroll_to(0, 2800)
                  splash:set_viewport_full()
                  splash:wait(5)
                  return {html=splash:html()}
                end
        """
        url = 'https://blog.csdn.net/'
        yield SplashRequest(url, self.parse,  endpoint='execute', args={'lua_source': script, 'url': url})

使用SplashRequest请求通过args传递参数,如果是scrapy.Request则是meta

然后还有一步就是将setting设置好(原来设置过,然后新的工程忘了设置,搞了好久才发现是这得问题)

# -*- coding: utf-8 -*-

# Scrapy settings for Technology project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'Technology'

SPIDER_MODULES = ['Technology.spiders']
NEWSPIDER_MODULE = 'Technology.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Technology (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'Technology.middlewares.TechnologySpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware':723,
    'scrapy_splash.SplashMiddleware':725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,#不配置查不到信息
   # 'Technology.middlewares.TechnologyDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'Technology.pipelines.TechnologyPipeline': 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
HTTPCACHE_ENABLED = True
HTTPCACHE_EXPIRATION_SECS = 0
HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
SPLASH_URL = "http://192.168.99.100:8050"      #自己安装的docker里的splash位置
DUPEFILTER_CLASS = "scrapy_splash.SplashAwareDupeFilter"
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

设置好以后就大功告成。

在前面的脚本那花费了好长时间,网上的资料都不全

安装docker见另一篇文章安装splash及解决点击Docker出现windows 正在查找bash.exe。如果想亲自查找文件,请点击“浏览”的问题

更多内容关注我的微信公众号

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
使用 Scrapy 和 Selenium 结合进行网页动态加载数据的爬取时,可以按照以下步骤进行操作: 1. 安装所需库:确保已安装 Scrapy 和 Selenium 库。可以使用以下命令进行安装: ``` pip install scrapy pip install selenium ``` 2. 创建 Scrapy 项目:使用以下命令创建一个新的 Scrapy 项目: ``` scrapy startproject dynamic_scraping ``` 3. 创建 Spider:进入项目目录,并使用以下命令创建一个新的 Spider: ``` cd dynamic_scraping scrapy genspider example example.com ``` 这将在 `spiders` 目录下创建一个名为 `example.py` 的 Spider。 4. 配置 Spider:打开 `example.py` 文件,并按照以下示例进行配置: ```python import scrapy from scrapy_selenium import SeleniumRequest from scrapy.selector import Selector class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['example.com'] def start_requests(self): yield SeleniumRequest( url='https://example.com', callback=self.parse ) def parse(self, response): sel = Selector(response) # 在这里使用 XPath 或 CSS 选择器提取动态加载的数据 # 示例:提取标题 title = sel.xpath('//h1/text()').get() print(title) ``` 在上面的示例中,我们使用了 `SeleniumRequest` 替代了普通的 `scrapy.Request`,这使得 Scrapy 可以使用 Selenium 来处理动态加载的内容。 5. 配置 Selenium:为了使用 Selenium,你需要配置相关的 Web 驱动程序。根据你使用的浏览器,下载并安装相应的驱动程序,并将其添加到系统的 PATH 环境变量中。 6. 运行 Spider:使用以下命令运行 Spider: ``` scrapy crawl example ``` 这将启动爬取过程,并在控制台上打印出提取的动态加载数据。 通过以上步骤,你可以使用 Scrapy 和 Selenium 结合进行爬取动态加载数据的操作。你可以根据实际需求修改 Spider 中的代码来提取所需的数据,并将其保存到文件或数据库中。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

裸睡的雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值