最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 詳解通過Scrapy框架實(shí)現(xiàn)爬取百度新冠疫情數(shù)據(jù)流程

 更新時(shí)間:2021年11月10日 14:07:52   作者:劍客阿良_ALiang  
Scrapy是用純Python實(shí)現(xiàn)一個(gè)為了爬取網(wǎng)站數(shù)據(jù)、提取結(jié)構(gòu)性數(shù)據(jù)而編寫的應(yīng)用框架,用途非常廣泛,框架的力量,用戶只需要定制開發(fā)幾個(gè)模塊就可以輕松的實(shí)現(xiàn)一個(gè)爬蟲,用來抓取網(wǎng)頁(yè)內(nèi)容以及各種圖片,非常之方便

前言

閑來無聊,寫了一個(gè)爬蟲程序獲取百度疫情數(shù)據(jù)。申明一下,研究而已。而且頁(yè)面應(yīng)該會(huì)進(jìn)程做反爬處理,可能需要調(diào)整對(duì)應(yīng)xpath。

Github倉(cāng)庫(kù)地址:代碼倉(cāng)庫(kù)

本文主要使用的是scrapy框架。

環(huán)境部署

主要簡(jiǎn)單推薦一下

插件推薦

這里先推薦一個(gè)Google Chrome的擴(kuò)展插件xpath helper,可以驗(yàn)證xpath語法是不是正確。

爬蟲目標(biāo)

需要爬取的頁(yè)面:實(shí)時(shí)更新:新型冠狀病毒肺炎疫情地圖

主要爬取的目標(biāo)選取了全國(guó)的數(shù)據(jù)以及各個(gè)身份的數(shù)據(jù)。

項(xiàng)目創(chuàng)建

使用scrapy命令創(chuàng)建項(xiàng)目

scrapy startproject yqsj

webdriver部署

這里就不重新講一遍了,可以參考我這篇文章的部署方法:Python 詳解通過Scrapy框架實(shí)現(xiàn)爬取CSDN全站熱榜標(biāo)題熱詞流程

項(xiàng)目代碼

開始擼代碼,看一下百度疫情省份數(shù)據(jù)的問題。

頁(yè)面需要點(diǎn)擊展開全部span。所以在提取頁(yè)面源碼的時(shí)候需要模擬瀏覽器打開后,點(diǎn)擊該按鈕。所以按照這個(gè)方向,我們一步步來。

Item定義

定義兩個(gè)類YqsjProvinceItem和YqsjChinaItem,分別定義國(guó)內(nèi)省份數(shù)據(jù)和國(guó)內(nèi)數(shù)據(jù)。

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
 
import scrapy
 
 
class YqsjProvinceItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    location = scrapy.Field()
    new = scrapy.Field()
    exist = scrapy.Field()
    total = scrapy.Field()
    cure = scrapy.Field()
    dead = scrapy.Field()
 
 
class YqsjChinaItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # 現(xiàn)有確診
    exist_diagnosis = scrapy.Field()
    # 無癥狀
    asymptomatic = scrapy.Field()
    # 現(xiàn)有疑似
    exist_suspecte = scrapy.Field()
    # 現(xiàn)有重癥
    exist_severe = scrapy.Field()
    # 累計(jì)確診
    cumulative_diagnosis = scrapy.Field()
    # 境外輸入
    overseas_input = scrapy.Field()
    # 累計(jì)治愈
    cumulative_cure = scrapy.Field()
    # 累計(jì)死亡
    cumulative_dead = scrapy.Field()

中間件定義

需要打開頁(yè)面后點(diǎn)擊一下展開全部。

完整代碼

# 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
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
import time
 
 
class YqsjSpiderMiddleware:
    # 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 YqsjDownloaderMiddleware:
    # 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
        try:
            spider.browser.get(request.url)
            spider.browser.maximize_window()
            time.sleep(2)
            spider.browser.find_element_by_xpath("http://*[@id='nationTable']/div/span").click()
            # ActionChains(spider.browser).click(searchButtonElement)
            time.sleep(5)
            return HtmlResponse(url=spider.browser.current_url, body=spider.browser.page_source,
                                encoding="utf-8", request=request)
        except TimeoutException as e:
            print('超時(shí)異常:{}'.format(e))
            spider.browser.execute_script('window.stop()')
        finally:
            spider.browser.close()
 
    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.
 
        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        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)

定義爬蟲

分別獲取國(guó)內(nèi)疫情數(shù)據(jù)以及省份疫情數(shù)據(jù)。完整代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/7 22:05
# @Author  : 至尊寶
# @Site    : 
# @File    : baidu_yq.py
 
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
 
from yqsj.items import YqsjChinaItem, YqsjProvinceItem
 
 
class YqsjSpider(scrapy.Spider):
    name = 'yqsj'
    # allowed_domains = ['blog.csdn.net']
    start_urls = ['https://voice.baidu.com/act/newpneumonia/newpneumonia#tab0']
    china_xpath = "http://div[contains(@class, 'VirusSummarySix_1-1-317_2ZJJBJ')]/text()"
    province_xpath = "http://*[@id='nationTable']/table/tbody/tr[{}]/td/text()"
    province_xpath_1 = "http://*[@id='nationTable']/table/tbody/tr[{}]/td/div/span/text()"
 
    def __init__(self):
        chrome_options = Options()
        chrome_options.add_argument('--headless')  # 使用無頭谷歌瀏覽器模式
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        self.browser = webdriver.Chrome(chrome_options=chrome_options,
                                        executable_path="E:\\chromedriver_win32\\chromedriver.exe")
        self.browser.set_page_load_timeout(30)
 
    def parse(self, response, **kwargs):
        country_info = response.xpath(self.china_xpath)
        yq_china = YqsjChinaItem()
        yq_china['exist_diagnosis'] = country_info[0].get()
        yq_china['asymptomatic'] = country_info[1].get()
        yq_china['exist_suspecte'] = country_info[2].get()
        yq_china['exist_severe'] = country_info[3].get()
        yq_china['cumulative_diagnosis'] = country_info[4].get()
        yq_china['overseas_input'] = country_info[5].get()
        yq_china['cumulative_cure'] = country_info[6].get()
        yq_china['cumulative_dead'] = country_info[7].get()
        yield yq_china
        
        # 遍歷35個(gè)地區(qū)
        for x in range(1, 35):
            path = self.province_xpath.format(x)
            path1 = self.province_xpath_1.format(x)
            province_info = response.xpath(path)
            province_name = response.xpath(path1)
            yq_province = YqsjProvinceItem()
            yq_province['location'] = province_name.get()
            yq_province['new'] = province_info[0].get()
            yq_province['exist'] = province_info[1].get()
            yq_province['total'] = province_info[2].get()
            yq_province['cure'] = province_info[3].get()
            yq_province['dead'] = province_info[4].get()
            yield yq_province

pipeline輸出結(jié)果文本

將結(jié)果按照一定的文本格式輸出出來。完整代碼:

# 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
 
from yqsj.items import YqsjChinaItem, YqsjProvinceItem
 
 
class YqsjPipeline:
    def __init__(self):
        self.file = open('result.txt', 'w', encoding='utf-8')
 
    def process_item(self, item, spider):
        if isinstance(item, YqsjChinaItem):
            self.file.write(
                "國(guó)內(nèi)疫情\n現(xiàn)有確診\t{}\n無癥狀\t{}\n現(xiàn)有疑似\t{}\n現(xiàn)有重癥\t{}\n累計(jì)確診\t{}\n境外輸入\t{}\n累計(jì)治愈\t{}\n累計(jì)死亡\t{}\n".format(
                    item['exist_diagnosis'],
                    item['asymptomatic'],
                    item['exist_suspecte'],
                    item['exist_severe'],
                    item['cumulative_diagnosis'],
                    item['overseas_input'],
                    item['cumulative_cure'],
                    item['cumulative_dead']))
        if isinstance(item, YqsjProvinceItem):
            self.file.write(
                "省份:{}\t新增:{}\t現(xiàn)有:{}\t累計(jì):{}\t治愈:{}\t死亡:{}\n".format(
                    item['location'],
                    item['new'],
                    item['exist'],
                    item['total'],
                    item['cure'],
                    item['dead']))
        return item
 
    def close_spider(self, spider):
        self.file.close()

配置文件改動(dòng)

直接參考,自行調(diào)整:

# Scrapy settings for yqsj 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 = 'yqsj'
 
SPIDER_MODULES = ['yqsj.spiders']
NEWSPIDER_MODULE = 'yqsj.spiders'
 
 
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'yqsj (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0'
 
# 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',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
}
 
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
   'yqsj.middlewares.YqsjSpiderMiddleware': 543,
}
 
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'yqsj.middlewares.YqsjDownloaderMiddleware': 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 = {
   'yqsj.pipelines.YqsjPipeline': 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'

驗(yàn)證結(jié)果

看看結(jié)果文件

總結(jié)

emmmm,閑著無聊,寫著玩,沒啥好總結(jié)的。

分享:

修心,亦是修行之一。順境修力,逆境修心,缺一不可。 ——《劍來》

如果本文對(duì)你有作用的話,不要吝嗇你的贊,謝謝。

以上就是Python 詳解通過Scrapy框架實(shí)現(xiàn)爬取百度新冠疫情數(shù)據(jù)流程的詳細(xì)內(nèi)容,更多關(guān)于Python Scrapy框架的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python實(shí)戰(zhàn)之Elasticsearch的高級(jí)實(shí)現(xiàn)詳解

    Python實(shí)戰(zhàn)之Elasticsearch的高級(jí)實(shí)現(xiàn)詳解

    Elasticsearch是一個(gè)功能強(qiáng)大的開源搜索引擎,廣泛應(yīng)用于各種場(chǎng)景,本文將深入探討如何使用Python與Elasticsearch進(jìn)行高級(jí)實(shí)現(xiàn),需要的可以參考下
    2024-04-04
  • Python異常?ValueError的問題

    Python異常?ValueError的問題

    這篇文章主要介紹了Python異常?ValueError的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 基于Python實(shí)現(xiàn)n-gram文本生成的示例代碼

    基于Python實(shí)現(xiàn)n-gram文本生成的示例代碼

    N-gram是自然語言處理中常用的技術(shù),它可以用于文本生成、語言模型訓(xùn)練等任務(wù),本文主要介紹了如何在Python中實(shí)現(xiàn)n-gram文本生成,需要的可以參考下
    2024-01-01
  • Python數(shù)據(jù)分析之?Pandas?Dataframe應(yīng)用自定義

    Python數(shù)據(jù)分析之?Pandas?Dataframe應(yīng)用自定義

    這篇文章主要介紹了Python數(shù)據(jù)分析之?Pandas?Dataframe應(yīng)用自定義,文章基于python的相關(guān)資料展開?Pandas?Dataframe應(yīng)用自定義的詳細(xì)內(nèi)容,需要的小伙伴可以參考一下
    2022-05-05
  • 基于Python實(shí)現(xiàn)牛牛套圈小游戲的示例代碼

    基于Python實(shí)現(xiàn)牛牛套圈小游戲的示例代碼

    “幸運(yùn)牛牛套圈圈”套住歡樂,圈住幸福,等你來挑戰(zhàn)!這篇文章小編主要為大家介紹一款基于Python實(shí)現(xiàn)牛牛套圈小游戲,感興趣的小伙伴可以了解一下
    2023-02-02
  • Python 實(shí)現(xiàn)簡(jiǎn)單的電話本功能

    Python 實(shí)現(xiàn)簡(jiǎn)單的電話本功能

    這篇文章主要介紹了Python 實(shí)現(xiàn)簡(jiǎn)單的電話本功能的相關(guān)資料,包括添加聯(lián)系人信息,查找姓名顯示聯(lián)系人,存儲(chǔ)聯(lián)系人到 TXT 文檔等內(nèi)容,十分的細(xì)致,有需要的小伙伴可以參考下
    2015-08-08
  • TensorFlow實(shí)現(xiàn)模型評(píng)估

    TensorFlow實(shí)現(xiàn)模型評(píng)估

    這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)模型評(píng)估,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • Python中還原JavaScript的escape函數(shù)編碼后字符串的方法

    Python中還原JavaScript的escape函數(shù)編碼后字符串的方法

    這篇文章主要介紹了Python中解析JavaScript的escape函數(shù)編碼后字符串的方法,即Python中如何還原JavaScript escape函數(shù)編碼后的字符串,需要的朋友可以參考下
    2014-08-08
  • Python手寫回歸樹的實(shí)現(xiàn)

    Python手寫回歸樹的實(shí)現(xiàn)

    本文主要介紹了Python手寫回歸樹的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 詳解python tkinter教程-事件綁定

    詳解python tkinter教程-事件綁定

    這篇文章主要介紹了python tkinter事件綁定,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03

最新評(píng)論

尚志市| 开阳县| 佛山市| 葵青区| 镇赉县| 罗甸县| 厦门市| 隆德县| 邳州市| 公安县| 临潭县| 睢宁县| 昌乐县| 黄平县| 会东县| 克山县| 大埔县| 油尖旺区| 常宁市| 体育| 慈利县| 乐都县| 西畴县| 冀州市| 高淳县| 和顺县| 广灵县| 浦江县| 综艺| 高台县| 仲巴县| 舟曲县| 沈丘县| 浑源县| 阆中市| 嘉祥县| 太和县| 同德县| 无为县| 昌乐县| 孝昌县|