欢迎来到赛兔子家园

selenium在scrapy中使用&爬取网易新闻

selenium在scrapy中的使用

示例:

需求:爬取网易新闻中的国内、国际,二个板块下所有的新闻数据(标题+内容)

地址:https://news.163.com/

爬取网站分析:

首页需要爬取2个板块对应的url,没有动态加载的数据

每一个板块对应的页面中新闻标题是【动态加载】,爬取新闻标题+详情页面的url

动态加载的数据,通过selenium来获取满足需求的响应数据,将其篡改到响应对象

每一条新闻详情页面中的数据不是动态加载,爬取的新闻内容

selenium在scrapy中使用流程

  1. 在爬虫类中实例化一个浏览器对象,将其作为爬虫类的一个属性
  2. 在中间中实现浏览器自动化相关的操作
  3. 在爬虫类中重写closed(self,spider),在其内部关闭浏览器对象

 spider.py

import scrapy

from selenium import webdriver
from myspider01.items import Myspider01Item


class NewsSpider(scrapy.Spider):
    name = 'news'
    # allowed_domains = ['www.baidu.com']
    start_urls = ['https://news.163.com/']
    model_urls = []
    # 实例化一个全局浏览器对象
    bro_obj = webdriver.Chrome()
    bro_obj.maximize_window()

    # 数据解析:每一个版块对应的url
    def parse(self, response):
        url_list = response.xpath('//*[@id="index2016_wrap"]/div[2]/div[2]/div[2]/div[2]/div/ul/li/a/@href')
        li_index = [1, 2]
        for index in li_index:
            print(index)
            self.model_urls.append(url_list[index].get())
        # 对每一个版块对应url发起请求
        print(self.model_urls)
        for url in self.model_urls:
            yield scrapy.Request(url, callback=self.parse_model)

    # 数据解析:新闻标题+新闻详情页面的url(动态加载数据)
    def parse_model(self, response):
        dev_list = response.xpath('/html/body/div/div[3]/div[3]/div[1]/div[1]/div/ul/li/div/div/div/div[1]/h3/a')
        for div in dev_list:
            title = div.xpath('./text()').get()
            new_detail_url = div.xpath('./@href').get()
            print("new_detail_url", new_detail_url)
            if new_detail_url:
                item = Myspider01Item()
                item["title"] = title
                yield scrapy.Request(url=new_detail_url, callback=self.parse_new_detail, meta={"item": item})

    def parse_new_detail(self, response):
        """
        解析新闻内容,不涉及动态加载数据
        :param response:
        :return:
        """
        content = response.xpath('//*[@id="content"]/div[2]/p/text()').extract()
        content = "".join(content)
        item = response.meta["item"]
        item["content"] = content
        yield item

    def closed(self, spider):
        self.bro_obj.quit()

piplines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class WangyiPipeline:
    def process_item(self, item, spider):
        print("进入",item)
        return item

items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class WangyiItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    content = scrapy.Field()

middlewares.py

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from time import sleep
from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class WangyiSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class WangyiDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # 所有的响应对象中找出需要篡改的2个响应对象,篡改响应内容
        if request.url in spider.model_urls:
            bro = spider.bro  # selenium中webdriver的浏览器对象
            # response指不满足需求的2个响应对象
            # 篡改响应数据:首先获取满足需求的响应数据,将其篡改到响应对象
            # 满足需求的响应数据就可以使用selenium获取
            bro.get(request.url)  # 使用selenium对五个板块的url发起请求
            sleep(2)
            bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
            sleep(1)
            # 捕获到板块页面中加载出来的全部数据
            page_text = bro.page_source
            # 方法1
            # response.text = page_text
            # return response
            # 方法2
            from scrapy.http import HtmlResponse  # scrapy封装好的响应类
            # 返回了一个新的响应对象,使用新的响应对象,替换原来不满足需求的响应对象
            return HtmlResponse(url=request.url, body=page_text, encoding="utf-8", request=request)

        else:
            return response


    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

settings.py

# Scrapy settings for wangyi project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'wangyi'

SPIDER_MODULES = ['wangyi.spiders']
NEWSPIDER_MODULE = 'wangyi.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'wangyi (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

LOG_LEVEL = "ERROR"  # 定义只输出错误的日志
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'wangyi.middlewares.WangyiSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'wangyi.middlewares.WangyiDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'wangyi.pipelines.WangyiPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

 

posted on 2021-07-27 21:34  赛兔子  阅读(59)  评论(0编辑  收藏  举报

导航