Monday, 4 March 2019

Scrapy splash spider not following links to fetch new pages

I am fetching data from a page that uses Javascript to link to new pages. I am using Scrapy + splash to fetch this data, however, for some reason, the links are not being followed.

Here is the code for my spider:

import scrapy
from   scrapy_splash import SplashRequest       

script = """
    function main(splash, args)
        local javascript = args.javascript
        assert(splash:runjs(javascript))
        splash:wait(0.5)

        return {
               html = splash:html()
        }
    end
"""


page_url = "https://www.londonstockexchange.com/exchange/prices-and-markets/stocks/exchange-insight/trade-data.html?page=0&pageOffBook=0&fourWayKey=GB00B6774699GBGBXAMSM&formName=frmRow&upToRow=-1"


class MySpider(scrapy.Spider):
    name = "foo_crawler"          
    download_delay = 5.0

    custom_settings = {
                'DOWNLOADER_MIDDLEWARES' : {
                            'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
                            'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
                            'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
                            },
                 #'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter'
                }




    def start_requests(self):
        yield SplashRequest(url=page_url, 
                                callback=self.parse
                            )



    # Parses first page of ticker, and processes all maturities
    def parse(self, response):
        try:
            self.extract_data_from_page(response)

            href = response.xpath('//div[@class="paging"]/p/a[contains(text(),"Next")]/@href')
            print("href: {0}".format(href))

            if href:
                javascript = href.extract_first().split(':')[1].strip()

                yield SplashRequest(response.url, self.parse, 
                                    cookies={'store_language':'en'},
                                    endpoint='execute', 
                                    args = {'lua_source': script, 'javascript': javascript })

        except Exception as err:
            print("The following error occured: {0}".format(err))



    def extract_data_from_page(self, response):
        url = response.url
        page_num = url.split('page=')[1].split('&')[0]
        print("extract_data_from_page() called on page: {0}.".format(url))
        filename = "page_{0}.html".format(page_num)
        with open(filename, 'w') as f:
            f.write(response.text)




    def handle_error(self, failure):
        print("Error: {0}".format(failure))

Only the first page is fetched, and I'm unable to get the subsequent pages by 'clicking' through the links at the bottom of the page.

How do I fix this so I can click through the pages given at the bottom of the page?



from Scrapy splash spider not following links to fetch new pages

No comments:

Post a Comment