【问题标题】:Python Web Scraping in Pagination in Single Page Application单页应用程序中分页中的 Python Web Scraping
【发布时间】:2021-06-23 13:43:09
【问题描述】:

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

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

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

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

请指教。

谢谢,

哈杰

【问题讨论】:

  • 你听说过 Selenium 吗?
  • 也通过 Selenium 进行研究。但是,我们想先探索 Scrapy。

标签: javascript python scrapy scrapy-splash


【解决方案1】:

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

通常情况下,网站会通过在网址末尾增加 ?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 和分页的教程。

【讨论】:

  • 感谢@TheGr8Destructo,这很有用。我会试试这个。
  • @TheGr8Destructo 那么你能直接去一个页面吗?目前我只是找到分页器(使用 Selenium)并单击“下一步”,直到我到达一个我之前没有处理过的页面并开始抓取。正如您可以想象的那样,处理的页面越多,每次新运行到达我离开的地方所需的时间就越长:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
相关资源
最近更新 更多