• 移动端疫情展示


    设计思想:

    首先利用python爬取疫情情况,然后用Android studio制作可视化界面。

    爬取代码:

    from os import path

    import request

    from bs4 import BeautifulSoup

    import json

    import pymysql

    import numpy as np

    import time

    import requests

    url = 'https://ncov.dxy.cn/ncovh5/view/pneumonia?from=timeline&isappinstalled=0'  # 请求地址

    headers = {

        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}  # 创建头部信息

    response = requests.get(url, headers=headers)  # 发送网络请求

    content = response.content.decode('utf-8')

    soup = BeautifulSoup(content, 'html.parser')

    listA = soup.find_all(name='script', attrs={"id": "getAreaStat"})

    # 世界确诊

    listB = soup.find_all(name='script', attrs={"id": "getListByCountryTypeService2"})

    account = str(listA)

    messages = account[52:-21]

    messages_json = json.loads(messages)

    valuesList = []

    cityList = []

    con = len(messages_json)

    k = 0

    for i in range(len(messages_json)):

        k = k + 1

        value = (

        k, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), messages_json[i].get('provinceShortName'), None,

        messages_json[i].get('confirmedCount'), messages_json[i].get('suspectedCount'), messages_json[i].get('curedCount'),

        messages_json[i].get('deadCount'), messages_json[i].get('locationId'))

        valuesList.append(value)

        cityValue = messages_json[i].get('cities')

        for j in range(len(cityValue)):

            con = con + 1

            cityValueList = (

            con, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), messages_json[i].get('provinceShortName'),

            cityValue[j].get('cityName'), cityValue[j].get('confirmedCount'), cityValue[j].get('suspectedCount'),

            cityValue[j].get('curedCount'), cityValue[j].get('deadCount'), cityValue[j].get('locationId'))

            cityList.append(cityValueList)

    db = pymysql.connect("localhost", "root", "123456", "yiqing1", charset='utf8')

    cursor = db.cursor()

    array = np.asarray(valuesList[0])

    sql_clean_province = "TRUNCATE TABLE info3"

    sql = "INSERT INTO info3 values (%s,%s,%s,%s,%s,%s,%s,%s,%s) "

    cityTuple = tuple(cityList)

    try:

        cursor.execute(sql_clean_province)

        db.commit()

    except:

        print('执行失败,进入回调1')

        db.rollback()

    try:

        cursor.executemany(sql, value_tuple)

        db.commit()

    except:

        print('执行失败,进入回调3')

        db.rollback()

    try:

        cursor.executemany(sql, cityTuple)

        db.commit()

    except:

        print('执行失败,进入回调4')

        db.rollback()

    db.close()

    截图:

     

    Android studio代码:

    package com.example.application;

    import androidx.appcompat.app.AppCompatActivity;

    import androidx.appcompat.app.AppCompatActivity;

    import android.annotation.SuppressLint;

    import android.app.Activity;

    import android.icu.lang.UCharacter;

    import android.os.Bundle;

    import android.os.Handler;

    import android.os.Message;

    import android.text.Editable;

    import android.text.TextWatcher;

    import android.view.View;

    import android.widget.AdapterView;

    import android.widget.ArrayAdapter;

    import android.widget.Button;

    import android.widget.EditText;

    import android.widget.ListView;

    import android.widget.Spinner;

    import android.widget.TextView;

    import java.sql.Connection;

    import java.sql.ResultSet;

    import java.sql.Statement;

    import java.util.ArrayList;

    import java.util.List;

    public class MainActivity extends AppCompatActivity {

        private Button bt_send;

        private EditText et_content;

        private static final int TEST_USER_SELECT = 1;

        private String content;

        private Spinner conditionSpinner;

        private String condition;

        private ListView lv;

        String[] strs = new String[]{};

        @SuppressLint("HandlerLeak")

        private Handler mHandler = new Handler(){

            @Override

            public void handleMessage(Message msg){

                switch(msg.what){

                    case TEST_USER_SELECT:

                        String s = (String)msg.obj;

                        strs = s.split("  ");

                        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,strs));

                        break;

                }

            }

        };

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            bt_send = findViewById(R.id.bt_send);

            et_content = findViewById(R.id.et_content);

            et_content.addTextChangedListener(new TextWatcher() {

                @Override

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override

                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override

                public void afterTextChanged(Editable s) {

                    content = s.toString();

                }

            });

            conditionSpinner = findViewById(R.id.condition);

            final String [] data = {"国家","时间"};

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,data);

            conditionSpinner.setAdapter(adapter);

            conditionSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

                @Override

                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    //取得选中的值

                    condition = data[position];

                    //设置显示当前选择的项

                    parent.setVisibility(View.VISIBLE);

                }

                @Override

                public void onNothingSelected(AdapterView<?> parent) {

                }

            });

            System.out.println(condition);

            lv = findViewById(R.id.lv);

        }

        @Override

        protected void onStart(){

            super.onStart();

            bt_send.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    //执行查询操作

                    //连接数据库进行操作需要在主线程操作

                    new Thread(new Runnable() {

                        @Override

                        public void run() {

                            //调用数据库帮助类中的方法取数据

                            List<Data> list = DB.searchDataByCountry(condition,content);

                            Message message = mHandler.obtainMessage();

                            String s = "";

                            for(int i=0;i<list.size();i++){

                                s += "时间:"+list.get(i).getLastUpdateTime()+"  ";

                                s += list.get(i).getCountryname()+"确诊人数为:  ";

                                s += list.get(i).getConfirmed()+"  ";

                            }

                            message.what = TEST_USER_SELECT;

                            message.obj = s;

                            mHandler.sendMessage(message);

                        }

                    }).start();

                }

            });

        }

    }

    package com.example.application;

    public class Data {

        private int id;

        private String countryname;

        private String confirmed;

        private String suspected;

        private String dead;

        private String healed;

        private String lastUpdateTime;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public String getCountryname() {

            return countryname;

        }

        public void setCountryname(String countryname) {

            this.countryname = countryname;

        }

        public String getConfirmed() {

            return confirmed;

        }

        public void setConfirmed(String confirmed) {

            this.confirmed = confirmed;

        }

        public String getSuspected() {

            return suspected;

        }

        public void setSuspected(String suspected) {

            this.suspected = suspected;

        }

        public String getDead() {

            return dead;

        }

        public void setDead(String dead) {

            this.dead = dead;

        }

        public String getHealed() {

            return healed;

        }

        public void setHealed(String healed) {

            this.healed = healed;

        }

        public String getLastUpdateTime() {

            return lastUpdateTime;

        }

        public void setLastUpdateTime(String lastUpdateTime) {

            this.lastUpdateTime = lastUpdateTime;

        }

    }

    package com.example.application;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    public class DB {

        private static String driver = "com.mysql.jdbc.Driver";

        private static String url = "jdbc:mysql://192.168.0.104:3306/yiqing1?characterEncoding=utf-8";

        private static String user = "root";//用户名

        private static String password = "123456";//密码

        public static Connection getConn(){

            Connection conn = null;

            try {

                Class.forName(driver);

                conn = (Connection) DriverManager.getConnection(url,user,password);//获取连接

            } catch (ClassNotFoundException e) {

                e.printStackTrace();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            return conn;

        }

        public static List<Data>  searchDataByCountry(String condition,String country_name){

            List<Data> list = new ArrayList<>();

            Connection connection = getConn();

            String sql = "";

            //System.out.println(condition);

            if(condition.equals("国家")){

                sql = "select * from worlddata where countryname like ?";

            }

            if(condition.equals("时间")){

                sql = "select * from worlddata where lastUpdateTime like ?";

            }

            System.out.println(country_name);

            if(connection !=null){

                try {

                    PreparedStatement ps = connection.prepareStatement(sql);

                    if(ps!=null){

                        ps.setString(1,"%"+country_name+"%");

                        ResultSet rs = ps.executeQuery();

                        if(rs!=null){

                            while(rs.next()){

                                Data data = new Data();

                                data.setId(rs.getInt("id"));

                                data.setCountryname(rs.getString("countryname"));

                                data.setConfirmed(rs.getString("confirmed"));

                                data.setSuspected(rs.getString("suspected"));

                                data.setDead(rs.getString("dead"));

                                data.setHealed(rs.getString("healed"));

                                data.setLastUpdateTime(rs.getString("lastUpdateTime"));

                                list.add(data);

                            }

                            connection.close();

                            ps.close();

                            return list;

                        }else{

                            return null;

                        }

                    }else{

                        return null;

                    }

                } catch (SQLException e) {

                    e.printStackTrace();

                    return null;

                }

            }else{

                return null;

            }

        }

    }

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

        xmlns:app="http://schemas.android.com/apk/res-auto"

        xmlns:tools="http://schemas.android.com/tools"

        android:orientation="vertical"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:context=".MainActivity">

        <Spinner

            android:id="@+id/condition"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            />

        <EditText

            android:id="@+id/et_content"

            android:layout_width="180dp"

            android:layout_height="40dp"

            android:layout_toRightOf="@+id/condition"

            />

        <Button

            android:id="@+id/bt_send"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:text="查询"

            android:layout_toRightOf="@+id/et_content"

            />

        <ListView

            android:id="@+id/lv"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:layout_marginTop="50dp"

            />

    </RelativeLayout>

  • 相关阅读:
    一个JAVA数据库连接池实现源码
    PL/SQL Developer去掉启动时自动弹出的Logon弹出框方法
    解决tomcat启动Socket监听端口死循环被hold问题
    JavaMelody应用监控使用指南
    ha456.jar打开dump文件报Unsupported major.minor version 51.0异常
    分布式并行数据库将在OLTP 领域促进去“Oracle”
    Oracle查找全表扫描的SQL语句
    Oracle 11g RAC客户端使用SCAN IP无法连接问题
    Oracle存储过程执行update语句不报错不生效问题
    Oracle外键不加索引会引起死锁问题
  • 原文地址:https://www.cnblogs.com/shumouren/p/13090355.html
Copyright © 2020-2023  润新知