Scrapy CrawlSpider 处理 AJAX 内容

13 投票
1 回答
15206 浏览
提问于 2025-04-18 06:49

我正在尝试抓取一个网站上的新闻文章。我的起始网址包含:

(1) 每篇文章的链接:http://example.com/symbol/TSLA

还有

(2) 一个“更多”按钮,这个按钮会发起一个AJAX请求,动态加载更多的文章,依然是在同一个起始网址下:http://example.com/account/ajax_headlines_content?type=in_focus_articles&page=0&slugs=tsla&is_symbol_page=true

这个AJAX请求有一个参数叫“page”,每次点击“更多”按钮时,这个参数会增加。例如,点击一次“更多”会加载额外的n篇文章,并在“更多”按钮的点击事件中更新“page”参数,这样下次点击“更多”时,就会加载“page” 2的文章(假设最开始加载的是“page” 0,第一次点击加载的是“page” 1)。

对于每一个“page”,我想用规则抓取每篇文章的内容,但我不知道总共有多少个“page”,也不想随便选择一个数字m(比如说10,000)。我似乎搞不清楚该怎么设置这个。

根据这个问题,Scrapy按顺序抓取网址,我尝试创建一个潜在网址的列表,但我无法确定在解析完前一个网址并确保它包含新闻链接后,应该如何以及在哪里发送一个新的网址。我的规则会把响应发送到一个解析项目的回调函数,在那里解析文章内容。

有没有办法在应用规则和调用解析项目之前观察链接页面的内容(类似于BaseSpider的例子),这样我就可以知道什么时候停止抓取?

简化的代码(为了清晰,我去掉了几个我正在解析的字段):

class ExampleSite(CrawlSpider):

    name = "so"
    download_delay = 2

    more_pages = True
    current_page = 0

    allowed_domains = ['example.com']

    start_urls = ['http://example.com/account/ajax_headlines_content?type=in_focus_articles&page=0'+
                      '&slugs=tsla&is_symbol_page=true']

    ##could also use
    ##start_urls = ['http://example.com/symbol/tsla']

    ajax_urls = []                                                                                                                                                                                                                                                                                                                                                                                                                          
    for i in range(1,1000):
        ajax_urls.append('http://example.com/account/ajax_headlines_content?type=in_focus_articles&page='+str(i)+
                      '&slugs=tsla&is_symbol_page=true')

    rules = (
             Rule(SgmlLinkExtractor(allow=('/symbol/tsla', ))),
             Rule(SgmlLinkExtractor(allow=('/news-article.*tesla.*', '/article.*tesla.*', )), callback='parse_item')
            )

        ##need something like this??
        ##override parse?
        ## if response.body == 'no results':
            ## self.more_pages = False
            ## ##stop crawler??   
        ## else: 
            ## self.current_page = self.current_page + 1
            ## yield Request(self.ajax_urls[self.current_page], callback=self.parse_start_url)


    def parse_item(self, response):

        self.log("Scraping: %s" % response.url, level=log.INFO)

        hxs = Selector(response)

        item = NewsItem()

        item['url'] = response.url
        item['source'] = 'example'
        item['title'] = hxs.xpath('//title/text()')
        item['date'] = hxs.xpath('//div[@class="article_info_pos"]/span/text()')

        yield item

1 个回答

13

Crawl spider 可能对你的需求来说有点局限。如果你需要更多的逻辑处理,通常继承 Spider 会更好。

Scrapy 提供了一个叫 CloseSpider 的异常,当你需要在某些条件下停止解析时,可以抛出这个异常。比如,当你爬取的页面返回一条信息“你的股票没有焦点文章”时,如果你超过了最大页面数,你可以检查这个信息,并在出现时停止爬取。

在你的情况下,你可以这样做:

from scrapy.spider import Spider
from scrapy.http import Request
from scrapy.exceptions import CloseSpider

class ExampleSite(Spider):
    name = "so"
    download_delay = 0.1

    more_pages = True
    next_page = 1

    start_urls = ['http://example.com/account/ajax_headlines_content?type=in_focus_articles&page=0'+
                      '&slugs=tsla&is_symbol_page=true']

    allowed_domains = ['example.com']

    def create_ajax_request(self, page_number):
        """
        Helper function to create ajax request for next page.
        """
        ajax_template = 'http://example.com/account/ajax_headlines_content?type=in_focus_articles&page={pagenum}&slugs=tsla&is_symbol_page=true'

        url = ajax_template.format(pagenum=page_number)
        return Request(url, callback=self.parse)

    def parse(self, response):
        """
        Parsing of each page.
        """
        if "There are no Focus articles on your stocks." in response.body:
            self.log("About to close spider", log.WARNING)
            raise CloseSpider(reason="no more pages to parse")


        # there is some content extract links to articles
        sel = Selector(response)
        links_xpath = "//div[@class='symbol_article']/a/@href"
        links = sel.xpath(links_xpath).extract()
        for link in links:
            url = urljoin(response.url, link)
            # follow link to article
            # commented out to see how pagination works
            #yield Request(url, callback=self.parse_item)

        # generate request for next page
        self.next_page += 1
        yield self.create_ajax_request(self.next_page)

    def parse_item(self, response):
        """
        Parsing of each article page.
        """
        self.log("Scraping: %s" % response.url, level=log.INFO)

        hxs = Selector(response)

        item = NewsItem()

        item['url'] = response.url
        item['source'] = 'example'
        item['title'] = hxs.xpath('//title/text()')
        item['date'] = hxs.xpath('//div[@class="article_info_pos"]/span/text()')

        yield item

撰写回答