首页 > 解决方案 > 单页应用程序中分页中的 Python Web Scraping

问题描述

我目前正在研究如何在单页应用程序 (SPA) 中由 javascript 驱动的分页中使用 python抓取网页内容。

例如, https://angular-8-pagination-example.stackblitz.io/

我搜索了一下,发现使用 Scrapy 无法抓取javascript / SPA 驱动的内容。它需要使用 Splash。我是 Scrapy 和 Splash 的新手。这个对吗?

另外,如何调用javascript分页方法?我检查了元素,它只是一个没有 href 和 javascript 事件的锚。

请指教。

谢谢,

哈吉

标签: javascriptpythonscrapyscrapy-splash

解决方案


您需要使用 SpalshRequest 来呈现 JS。然后,您需要获取分页文本。通常我使用 re.search 和适当的正则表达式模式来提取相关数字。然后,您可以将它们分配给当前页面变量和总页面变量。

通常,网站将通过在 url 末尾增加 ?page=x 或 ?p=x 来移动到下一页。然后,您可以增加此值以抓取所有相关页面。

整体模式如下所示:

import scrapy
from scrapy_splash import SplashRequest
import re

from ..items import Item

proxy ='http//your.proxy.com:PORT'

current_page_xpath='//div[your x path selector]/text()'
last_page_xpath='//div[your other x path selector]/text()'

class spider(scrapy.Spider):

    name = 'my_spider'
    allowed_domains =['domain.com']

    start_urls =['https://www.domaintoscrape.com/page=1']
                 
    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url=url, callback=self.parse, meta ={'proxy':proxy})

     def get_page_nbr(value):
  
      #you may need more complex regex to get page numbers.
      #most of the time they are in form "page X of Y"
      #google is your friend

      if re.search('\d+',value):
           value = re.search('\d+',value)
           value = value[0]
      else:
           value =None
      return  value

    def parse(self, response):
            #get last and current page from response:

            last_page = page_response.xpath(last_page_xpath).get()
            current_page = page_response.xpath(current_page_xpath).get()

            #do something with your response 
            # if current page is less than last page make another request by incrmenenting the page in the URL

            if current_page < last_page:
                ajax_url = response.url.replace(f'page={int(current_page)}',f'page={int(current_page)+1}')
                yield scrapy.Request(url=ajax_url, callback=self.parse, meta ={'proxy':proxy})

            #optional
            if current_page == last_page:
                print(f'processed {last_page} items for {response.url}')

最后,值得在 Youtube 上看看,因为有很多关于 scrapy_splash 和 pagination 的教程。


推荐阅读