爬取网易新闻

12 篇文章 3 订阅

爬取网易新闻

wangyi.py

import scrapy
from selenium import webdriver

from wangyiPro.items import WangyiproItem

'''
    可以尝试用这个项目做boss直聘的项目
    python期末作业 空气质量分析也可以参考
'''
class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['www.wngyi.com']
    start_urls = ['https://news.163.com/']
    model_urls = []

    # 实例化浏览器对象
    def __init__(self):
        self.bro = webdriver.Chrome(executable_path='D:\Python work space\ Reptile\Scrapy框架\chromedriver.exe')

    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]
        alist = [3]
        for index in alist:
            model_url = li_list[index].xpath('./a/@href').extract_first()
            self.model_urls.append(model_url)

        # 依次对每一个板块的页面进行请求
        for url in self.model_urls:
            yield scrapy.Request(url,callback=self.parse_model)

    # 每一个板块对应的新闻标题相关的内容都是动态加载的
    # 解析每一个板块页面中对应新闻的标题和新闻详情页的url
    def parse_model(self,response):
        div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div')
        for div in div_list:
            title = div.xpath('./div/div[1]/h3/a/text()').extract_first()
            new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first()
            item = WangyiproItem()
            item['title'] = title
            # 利用meta将item传递给
            # 对新闻详情页的url发起请求
            yield scrapy.Request(url=new_detail_url,callback=self.parse_detail,meta={'item':item})
            break
    # 解析新闻内容
    def parse_detail(self,response):
        content = response.xpath('//*[@class="post_body"]//text()').extract()
        content = ''.join(content)
        item = response.meta['item']
        item['content'] = content

        yield item

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

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

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

import time


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):  # spider爬虫对象 爬虫文件中实例化单独对象
        # 挑选出指定的响应对象进行篡改
        # 通过url指定request
        # 通过request指定response
        bro = spider.bro  # 获取了在爬虫类中定义的浏览器对象

        if request.url in spider.model_urls:
            bro.get(request.url)  # 对五大板块对应的url进行请求
            time.sleep(3)
            page_text = bro.page_source  # 包含动态加载的数据

            # response 五大板块对应的响应数据
            # 针对定位到的这些response进行篡改
            # 实例化一个新的响应对象(符合要求的:包含动态架加载出来的新闻数据) 取代原来的旧数据
            # 基于selenium便捷的获取动态加载数据
            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):
  
        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):
        with open('./wangyi.txt','w',encoding='utf-8') as fp:
            fp.write(item['title']+item['content'])
        print("item['title']"+item['title'])

        print("item['content']"+item['content'])
        return item

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼干儿♛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值