📜  Python – 各国冠状病毒病例的详细信息

📅  最后修改于: 2022-05-13 01:55:37.605000             🧑  作者: Mango

Python – 各国冠状病毒病例的详细信息

在本文中,我们将了解如何编写脚本来获取冠状病毒病例的详细信息,即仅通过输入国家名称来获取病例总数、康复病例和总死亡人数。

所需模块和安装:

Requests : Requests 允许您非常轻松地发送 HTTP/1.1 请求。无需手动将查询字符串添加到您的 URL。

pip install requests

Beautiful Soup: Beautiful Soup 是一个库,可以轻松地从网页中抓取信息。它位于 HTML 或 XML 解析器之上,提供用于迭代、搜索和修改解析树的 Pythonic 习惯用法。

pip install beautifulsoup4

下面是实现——

Python3
# importing libraries
from bs4 import BeautifulSoup as BS
import requests
  
  
# method to get the info
def get_info(country_name):
      
    # creating url using country name
    url = "https://www.worldometers.info/coronavirus/country/" + country_name + "/"
      
    # getting the request from url 
    data = requests.get(url)
  
    # converting the text 
    soup = BS(data.text, 'html.parser')   
      
    # finding meta info for cases
    cases = soup.find_all("div", class_ = "maincounter-number")
      
    # getting total cases number
    total = cases[0].text
      
    # filtering it
    total = total[1 : len(total) - 2]
       
    # getting recovered cases number
    recovered = cases[2].text
      
    # filtering it
    recovered = recovered[1 : len(recovered) - 1]
      
      
    # getting death cases number
    deaths = cases[1].text
      
    # filtering it
    deaths = deaths[1 : len(deaths) - 1]
      
    # saving details in dictionary
    ans ={'Total Cases' : total, 'Recovered Cases' : recovered,
                                 'Total Deaths' : deaths}
      
    # returning the dictionary
    return ans
   
# setting country name
country_name = "us"
  
# calling the get_info method
us = get_info(country_name)
  
# printing the results for us
print("Cases in United States")
for i, j in us.items():
    print(i + " : " + j)
      
print("----------------------------")  
# setting country name to india
country_name = "india"
  
# calling the get_info method
india = get_info(country_name)
  
# printing the results for us
print("Cases in India")
for i, j in india.items():
    print(i + " : " + j)


输出 :

Cases in United States
Total Cases : 654,343
Recovered Cases : 56,618
Total Deaths : 33,490
----------------------------
Cases in India
Total Cases : 12,759
Recovered Cases : 1,514
Total Deaths : 423