栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

爬虫学习日志11--获取疫情数据并保存--封装

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

爬虫学习日志11--获取疫情数据并保存--封装

前言

这篇文章主要讲述如何封装疫情爬虫函数,并且获取多日的疫情数据

一、代码
#跟着视频学习的代码,记录分享一下
# 获取数据-解析数据-保存数据
import requests
from bs4 import BeautifulSoup
import re
import json
from tqdm import tqdm

class CoronaVirusSpider(object):

      def _init_(self):
           self.home_url='https://ncov.dxy.cn/ncovh5/view/pneumonia'

      def get_content_from_url(self,url):
            '''
            根据URL,获取响应内容的字符串数据
            :param url:请求的URL
            :return: 响应内容的字符串
            '''
            #1.发送请求,获取疫情首页
            response = requests.get(url)
            return response.content.decode()

      def parse_home_page(self,home_page,tag_id):
            """
            解析首页内容,获取解析后的Python数据

            :param home_page:首页的内容
            :return:解析后的python数据
            """
            #2.从疫情首页,提取最近一日各国疫情数据
            soup = BeautifulSoup(home_page,'lxml')
            script=soup.find(id=tag_id)
            text=script.text
            print(text)
            #3.从疫情数据中,获取json格式的字符串
            json_str=re.findall(r'[.+]',text)[0]
            #print(json_str)
            #4.把json格式的字符串转换为python类型
            data=json.loads(json_str)
            return data

      def parse_corona_virus(self, last_day_corona_virus_of_china,desc):
          # 定义列表
          corona_virus = []
          for country in tqdm(last_day_corona_virus_of_china, desc):
              # 3.发送请求,获取各省疫情json字符串
              statistics_data_url = country['statisticsData']
              statistics_data_json_str = self.get_content_from_url(statistics_data_url)
              # print(statistics_data_json_str)
              # 4.解析各省疫情json字符串,并添加列表中
              statistics_data = json.loads(statistics_data_json_str)['data']
              # print(statistics_data)
              for one_day in statistics_data:
                  one_day['provinceName'] = country['provinceName']
                  if country.get('countryShortCode'):
                      one_day['countryShortCode']=country['countryShortCode']
              # print(statistics_data)
              corona_virus.extend(statistics_data)
              # print(corona_virus)
          return corona_virus

      def load(self,path):
          '''
          根据路径加载数据
          :param path:
          :return:
          '''
          with open(path, encoding='utf-8') as fp:
            data=json.load(fp)
          return data

      def save(self, data, path):
            # print(last_day_corona_virus)
            # 5.以json格式保存最近一日各国疫情数据
            with open(path, 'w', encoding='utf-8') as fp:
                  json.dump(data, fp, ensure_ascii=False)

      def crawl_last_day_corona_virus(self):
            """
            采集各国疫情数据
            :return:
            """
            #1.发送请求,获取首页内容
            home_page=self.get_content_from_url(self.home_url)
            #2.解析首页内容,获取最近一天的各国疫情数据
            last_day_corona_virus=self.parse_home_page(home_page,tag_id='getListByCountryTypeService2true')
            #3.保存数据
            self.save(last_day_corona_virus,'venv/last_day_corona_virus.json')

      def crawl_last_day_corona_virus_of_china(self):
            """
            采集最近一日各省疫情数据
            """
            #1.发送请求,获取疫情首页
            home_page=self.get_content_from_url(self.home_url)
            #2.解析疫情首页,获取最近一日各省疫情数据

            last_day_corona_virus_of_china=self.parse_home_page(home_page,tag_id= 'getAreaStat')

            #3.保存疫情数据
            self.save(last_day_corona_virus_of_china,'venv/last_day_corona_virus_of_china.json')


      def crawl_corna_vius(self):
            """
            采集从1月23号以来各国疫情数据
            :return:
            """
            #1.加载各国疫情数据

            last_day_corona_virus=self.load('venv/last_day_corona_virus.json')
            print(last_day_corona_virus)
            #定义列表,用于存储各国从1月23日以来的疫情数据
            corona_virus=self.parse_corona_virus(last_day_corona_virus,desc='采集1月23日以来的各国疫情信息')
                # 5.把列表以json格式保存为文件
            self.save(corona_virus,'venu/corona_virus.json')

      def crawl_corona_virus_of_china(self):
       '''
       采集从1月22日以来的全国各省的疫情数据
       :return:
       '''
       #1.加载最近一日全国疫情信息
       last_day_corona_virus_of_china = self.load('venv/last_day_corona_virus_of_china.json')
       #2.遍历最近一日全国疫情信息,获取各省疫情URL
       corona_virus = self.parse_corona_virus(last_day_corona_virus_of_china,'采集1月22日以来各省疫情信息')

       #5.以json格式保存疫情信息
       self.save(corona_virus, 'venv/corona_virus_of_china.json')



      def run(self):
           #self.crawl_last_day_corona_virus()
           #self.crawl_corna_vius()
          #self.crawl_last_day_corona_virus_of_china()
          self.crawl_corona_virus_of_china()()

if __name__=='__main__':
      spider=CoronaVirusSpider()
      spider._init_()
      spider.run()
总结

最终获取到的数据会保存在venv文件夹中,大家如果文件夹不同需要在最后修改一下路径的名字。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738622.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号