Wednesday, 24 November 2021

DOWNLOADER_MIDDLEWARE not determining order of middleware

I have the following spider which runs fine:


from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class SpiderOp(CrawlSpider):

    name = "upcoming"
    start_urls = ["https://www.oddsportal.com/tennis/"]
    
    custom_settings = {
        "USER_AGENT": "*",
        "LOG_LEVEL": "WARNING",
    }
    linkxtr = LinkExtractor(allow="/tennis/", restrict_xpaths=("//table[contains(@class, 'table-main sport')]"))
    rules = (Rule(linkxtr, callback="parse_tournaments", follow=True), )
    httperror_allowed_codes = [301]
        
    def parse_tournaments(self, response):
        print(response.url)


process = CrawlerProcess()
process.crawl(SpiderOp)
process.start()

However, some of the pages on the site I scrape only fully render once some Javascript has executed. From reading around the easiest way to get around this is to use a headless browser so I've been trying to follow the solution here to set up Selenium as a middleware in my Scrapy scraper.

To that end I've added this to the middleware.py file:

class SeleniumMiddleware:

    def __init__(self):
        options = webdriver.FirefoxOptions()
        options.add_argument("--headless")
        self.driver = webdriver.Firefox(options=options)

    def process_request(self, request, spider):
        print(f"Selenium processing request - {request.url}")
        self.driver.get(request.url)
        body = self.driver.page_source
        return HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=request)

I've also added the following line to the custom_settings dictionary of my spider:

"DOWNLOADER_MIDDLEWARES": {'scraper_scrapy.middlewares.SeleniumMiddleware': 1000}

However, I'm finding that Selenium scrapes all pages on the site including the non-Javascript ones which I don't want because it is slow. As mentioned at the start of this post the standard middlewares can handle this. My understanding from the docs is that middleware should be executed in sequential order according to their value until one returns a response? If that's the case then the item I added to custom_settings should be run after all the other middlewares have been tried?

Any ideas on what I could be doing wrong?

Scrapy is 2.4.1, Python is 3.9.6 and Mac OSX Monterey on 2016 MacBook Pro.



from DOWNLOADER_MIDDLEWARE not determining order of middleware

No comments:

Post a Comment