scrapy框架+selenium的使用

scrapy框架+selenium的使用

1 使用情景:   

  在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值。但是通过观察我们会发现,通过浏览器进行url请求发送则会加载出对应的动态加载出的数据。那么如果我们想要在scrapy也获取动态加载出的数据,则必须使用selenium创建浏览器对象,然后通过该浏览器对象进行请求发送,获取动态加载的数据值

 2 使用流程

  1 重写爬虫文件的__init__()构造方法,在该方法中使用selenium实例化一个浏览器对象(因为浏览器对象只需要被实例化一次).

  2 重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象,该方法是在爬虫结束时被调用.

  3 重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据.

  4 在settings配置文件中开启下载中间件

3 使用案例: 爬取XXX网站新闻的部分板块内容

  爬虫文件: 

# 注意:这里对请求进行初始化后,每一次请求都是使用selenium

from selenium import webdriver
from  selenium.webdriver.chrome.options import Options    # 使用无头浏览器
import scrapy
无头浏览器设置
chorme_options = Options()
chorme_options.add_argument("--headless")
chorme_options.add_argument("--disable-gpu")


class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['wangyi.com']   # 允许爬取的域名
    start_urls = ['https://news.163.com/']

    # 实例化一个浏览器对象
    def __init__(self):
        self.browser = webdriver.Chrome(chrome_options=chorme_options)
        super().__init__()

    def start_requests(self):
        url = "https://news.163.com/"
        response = scrapy.Request(url,callback=self.parse_index)
        yield response

    # 整个爬虫结束后关闭浏览器
    def close(self,spider):
        self.browser.quit()

    # 访问主页的url, 拿到对应板块的response
    def parse_index(self, response):
        div_list = response.xpath("//div[@class='ns_area list']/ul/li/a/@href").extract()
        index_list = [3,4,6,7]
        for index in index_list:
            response = scrapy.Request(div_list[index],callback=self.parse_detail)
            yield response

    # 对每一个板块进行详细访问并解析, 获取板块内的每条新闻的url
    def parse_detail(self,response):
        div_res = response.xpath("//div[@class='data_row news_article clearfix ']")
        # print(len(div_res))
        title = div_res.xpath(".//div[@class='news_title']/h3/a/text()").extract_first()
        pic_url = div_res.xpath("./a/img/@src").extract_first()
        detail_url = div_res.xpath("//div[@class='news_title']/h3/a/@href").extract_first()
        infos = div_res.xpath(".//div[@class='news_tag//text()']").extract()
        info_list = []
        for info in infos:
            info = info.strip()
            info_list.append(info)
        info_str = "".join(info_list)
        item = WangyiproItem()

        item["title"] = title
        item["detail_url"] = detail_url
        item["pic_url"] = pic_url
        item["info_str"] = info_str

        yield scrapy.Request(url=detail_url,callback=self.parse_content,meta={"item":item})    # 通过 参数meta 可以将item参数传递进 callback回调函数,再由 response.meta[...]取出来

    # 对每条新闻的url进行访问, 并解析
    def parse_content(self,response):
        item = response.meta["item"]    # 获取从response回调函数由meta传过来的 item 值
        content_list = response.xpath("//div[@class='post_text']/p/text()").extract()
        content = "".join(content_list)
        item["content"] = content
        yield item
原文地址:https://www.cnblogs.com/wukai66/p/13288211.html