抓取网页时如何单击下一步按钮

时间:2019-05-22 13:25:28

标签: python web-scraping scrapy splash

我正在使用scrapy抓取具有多个信息页面的网页,我需要程序单击next按钮,然后抓取下一页,然后继续这样做,直到抓取所有页面为止。但是我不知道该怎么做,只能刮第一页。

from scrapy_splash import SplashRequest
from ..items import GameItem

class MySpider(Spider):
        name = 'splash_spider' # Name of Spider
        start_urls = ['http://www.starcitygames.com/catalog/category/10th%20Edition'] # url(s)
        def start_requests(self):
                for url in self.start_urls:
                        yield SplashRequest(url=url, callback=self.parse, args={"wait": 3})
        #Scraping
        def parse(self, response):
                item = GameItem()
                for game in response.css("tr"):
                        # Card Name
                        item["Name"] = game.css("a.card_popup::text").extract_first()
                        # Price
                        item["Price"] = game.css("td.deckdbbody.search_results_9::text").extract_first()
                        yield item

3 个答案:

答案 0 :(得分:1)

Documentation非常明确:

from scrapy_splash import SplashRequest
from ..items import GameItem

class MySpider(Spider):
        name = 'splash_spider' # Name of Spider
        start_urls = ['http://www.starcitygames.com/catalog/category/10th%20Edition'] # url(s)
        def start_requests(self):
            for url in self.start_urls:
                yield SplashRequest(url=url, callback=self.parse, args={"wait": 3})
        #Scraping
        def parse(self, response):
            item = GameItem()
            for game in response.css("tr"):
                # Card Name
                item["Name"] = game.css("a.card_popup::text").extract_first()
                # Price
                item["Price"] = game.css("td.deckdbbody.search_results_9::text").extract_first()
                yield item

            next_page = response.css(<your css selector to find next page>).get()
            if next_page is not None:
                yield response.follow(next_page, self.parse)

答案 1 :(得分:1)

您可以使用css选择器定位下一个按钮

a:nth-of-type(7)

第n个孩子

a:nth-child(8)

答案 2 :(得分:1)

您可以像下面这样使它工作:

import scrapy

class GameSpider(scrapy.Spider):
        name = 'game_spider'
        start_urls = ['http://www.starcitygames.com/catalog/category/10th%20Edition'] 

        def parse(self, response):
                for game in response.css("tr.deckdbbody_row"):
                        yield {
                                'name': game.css("a.card_popup::text").get(),
                                'price': game.css(".search_results_9::text").get(),
                        }
                next_page_url = response.css('table+ div a:nth-child(8)::attr(href)').get()
                if next_page_url is not None:
                        yield response.follow(next_page_url, self.parse)