python - Scrapy - 在第一次请求后禁用 Selenium

标签 python selenium scrapy

我正在从网站上抓取网址,但只有第一个请求需要 Selenium ,而其他请求则不需要。是否可以在抓取过程中关闭 Selenium?我想这样做,因为,就像你现在可能一样,Selenium 大大减慢了抓取过程。这是蜘蛛的代码:

class StoreSpider(scrapy.Spider):
    name = 'store'
    allowed_domains = ['www.store.com.br']
    custom_settings = {
        'COLLECTION_NAME'   : 'store',
        'URLS_COLLECTION_NAME'   : 'store_urls',
        'USES_SELENIUM'          : True,
        'HEADLESS'               : True,
        'DOWNLOADER_MIDDLEWARES': {
            'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90,
            'navigator.middlewares.SeleniumMiddleware': 700,
        }
    }

    categories_le = LinkExtractor(restrict_xpaths="//li[@class='h3']/a[not(@id)]")

    def start_requests(self):
        urls = [
            'https://www.store.com.br/loja/mapa-do-site',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse_categories)

最佳答案

您可以修改您的中间件,使其仅在请求带有 render_js 元键时才使用 Selenium。

类似这样的事情:

class SeleniumMiddleware(object):
    ...
    def process_request(self, request, spider):
        if not request.meta.get('render_js'):
            # disable js rendering in a per-request basis
            return

        # render with selenium
        ...

这是有效的,因为当下载器中间件的 process_request 返回 None 时,请求将继续到链中的下一个中间件,最终到达 Scrapy 的下载器。

更多信息请点击:https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#scrapy.downloadermiddlewares.DownloaderMiddleware.process_request

关于python - Scrapy - 在第一次请求后禁用 Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631469/

相关文章:

python - 列表的子列表

perl - 无法使用 Selenium 自动化 SWF 组件

python - 如何下载html表格内容?

python - 使用 Headless Chrome Webdriver 运行 Selenium

python - Selenium Python 跳过 NoSuchElementException 错误

python - Scrapy POST 请求不工作 - 400 错误请求

Python/Scrapy/Selenium/PhantomJs - 性能

python - 为什么列表结果与预期不同?

python - Tensorflow 2.0-GPU Windows 在CPU上运行训练代码

Python 解释器在 Powershell ISE 中崩溃