Python scrapy+selenium实现网易新闻爬取

wangyi.py爬虫文件

import scrapy
from selenium import webdriver
from wangyipro.items import WangyiproItem
class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://news.163.com/']
    models_urls = []
    # 实例化浏览器对象
    def __init__(self):
        path = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver'
        self.bro = webdriver.Chrome(path)
    def parse(self, response):
        li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul/li')
        alist = [3,4,6,7,8]
        for index in alist:
            model_url = li_list[index].xpath('./a/@href').extract_first()
            self.models_urls.append(model_url)
        # 发请求
        for url in self.models_urls:
            yield scrapy.Request(url,callback = self.parse_model)
    # 解析标题和详情页
    def parse_model(self,response):
        page_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div/div/ul/li/div/div | /html/body/div/div[3]/div[2]/div[2]/div[1]/div[1]/div/ul/li/div/div')
        t = response.xpath('/html/body/div/div[3]/div[2]/div[1]/span/span/text() | /html/body/div/div[3]/div[1]/div[1]/span/span/text()')
        # print(t)
        for url in page_list:
            title = url.xpath('.//h3/a/text()').extract_first()
            new_url = url.xpath('.//h3/a/@href').extract_first()
            item = WangyiproItem()
            item['title'] = title
            yield scrapy.Request(new_url,callback = self.parse_detail,meta = {'item':item})
    def parse_detail(self,response):
       content = response.xpath('//*[@id="content"]/div[2]//text()').extract()
       content = ''.join(content)
       item = response.meta['item']
       item['content'] = content
       yield item
    def closed(self,spider):
       self.bro.quit()
               

settings.py配置文件

# Scrapy settings for wangyipro 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 = 'wangyipro'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'wangyipro (+http://www.yourdomain.com)'
LOG_LEVEL = 'ERROR'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# 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 = {
#    'wangyipro.middlewares.WangyiproSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'wangyipro.middlewares.WangyiproDownloaderMiddleware': 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 = {
   'wangyipro.pipelines.WangyiproPipeline': 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'

middlewares.py(下载)中间件

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

from scrapy import signals
from scrapy.http import HtmlResponse
from time import sleep
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter

class WangyiproDownloaderMiddleware:
    # 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.
    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):
        bro = spider.bro  # 获取爬虫类中浏览器对象
        if request.url in spider.models_urls:
            bro.get(request.url)
            sleep(2)
            # 新响应数据
            page_text = bro.page_source
            new_response = HtmlResponse(url= request.url,body = page_text,encoding = 'utf-8',request= request)
            return new_response
        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

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 WangyiproItem(scrapy.Item):
    # define the fields for your item here like:
    title = scrapy.Field()
    content = scrapy.Field()
    pass

pipelines.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 WangyiproPipeline:
    def process_item(self, item, spider):
        print(item)
        return item

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用 ScrapySelenium 结合进行网页动态加载数据的爬取时,可以按照以下步骤进行操作: 1. 安装所需库:确保已安装 ScrapySelenium 库。可以使用以下命令进行安装: ``` pip install scrapy pip install selenium ``` 2. 创建 Scrapy 项目:使用以下命令创建一个新的 Scrapy 项目: ``` scrapy startproject dynamic_scraping ``` 3. 创建 Spider:进入项目目录,并使用以下命令创建一个新的 Spider: ``` cd dynamic_scraping scrapy genspider example example.com ``` 这将在 `spiders` 目录下创建一个名为 `example.py` 的 Spider。 4. 配置 Spider:打开 `example.py` 文件,并按照以下示例进行配置: ```python import scrapy from scrapy_selenium import SeleniumRequest from scrapy.selector import Selector class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['example.com'] def start_requests(self): yield SeleniumRequest( url='https://example.com', callback=self.parse ) def parse(self, response): sel = Selector(response) # 在这里使用 XPath 或 CSS 选择器提取动态加载的数据 # 示例:提取标题 title = sel.xpath('//h1/text()').get() print(title) ``` 在上面的示例中,我们使用了 `SeleniumRequest` 替代了普通的 `scrapy.Request`,这使得 Scrapy 可以使用 Selenium 来处理动态加载的内容。 5. 配置 Selenium:为了使用 Selenium,你需要配置相关的 Web 驱动程序。根据你使用的浏览器,下载并安装相应的驱动程序,并将其添加到系统的 PATH 环境变量中。 6. 运行 Spider:使用以下命令运行 Spider: ``` scrapy crawl example ``` 这将启动爬取过程,并在控制台上打印出提取的动态加载数据。 通过以上步骤,你可以使用 ScrapySelenium 结合进行爬取动态加载数据的操作。你可以根据实际需求修改 Spider 中的代码来提取所需的数据,并将其保存到文件或数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值