scrapy中使用selenium来爬取页面

Posted ivy-blogs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scrapy中使用selenium来爬取页面相关的知识,希望对你有一定的参考价值。

scrapy中使用selenium来爬取页面

from selenium import webdriver
from scrapy.http.response.html import HtmlResponse


class JianShuDownloaderMiddleware:
    def __init__(self):
        self.driver = webdriver.Chrome()

    def process_request(self, request, spider):
        self.driver.get(request.url)
        response = HtmlResponse(
            url=self.driver.current_url,
            body=self.driver.page_source,
            encoding='utf-8',
        )
        return response
  • scrapy中如果下载中间件的process_request返回的是一个response对象,那么它会直接将该response返回
  • 在这里利用selenium将网页渲染过的html抓取下来,然后在将其转换为scrapy所能解析的response对象
  • 最后在spider中的parse方法中拿到的response对象就是这里抓取到的response
  • 开启中间件需要在setting中配置,或者在spider中通过custom_settings来进行开启

以上是关于scrapy中使用selenium来爬取页面的主要内容,如果未能解决你的问题,请参考以下文章