思路:

    Android连接MySQL数据库获取数据;

    按时间查询全球疫情信息,或按国家查询;

    爬取信息的代码直接再上一次的基础上修改;

import requests
import time, json
import sys;
import pymysql

def get_wangyi_request():
    url = 'https://c.m.163.com/ug/api/wuhan/app/data/list-total'

    headers = {
        'accept': '*/*',
        'accept-encoding': 'gzip,deflate,br',
        'accept-language': 'en-US,en;q=0.9,zh-CN;q = 0.8,zh;q = 0.7',
        'origin': 'https://wp.m.163.com',
        'referer': 'https://wp.m.163.com/',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-ite',
        'user-agent': 'Mozilla/5.0(WindowsNT10.0;Win64;x64) AppleWebKit/37.36 (KHTML, likeGecko) Chrome/82.0.4056.0 Safari/537.36 Edg/82.0.432.3'
    }

    result = requests.get(url, headers=headers)
    return result


def print_mess1(string: str, dict1total: dict):
    sys.stdout.write(string + '确诊: ' + str(dict1total['confirm'] if dict1total['confirm'] != None else 0))
    sys.stdout.write(' ')
    sys.stdout.write(string + '疑似: ' + str(dict1total['suspect'] if dict1total['suspect'] != None else 0))
    sys.stdout.write(' ')
    sys.stdout.write(string + '治愈: ' + str(dict1total['heal'] if dict1total['heal'] != None else 0))
    sys.stdout.write(' ')
    sys.stdout.write(string + '死亡: ' + str(dict1total['dead'] if dict1total['dead'] != None else 0))


if __name__ == '__main__':
    result = get_wangyi_request()

    json_str = json.loads(result.text)['data']
    # print(json_str.keys())
    # dict_keys(['chinaTotal', 'chinaDayList', 'lastUpdateTime', 'areaTree'])

    print(json_str['lastUpdateTime'])
    countryname_list = json_str['areaTree']
    # 每个省份包含如下的键
    # dict_keys(['today', 'total', 'extData', 'name', 'id', 'lastUpdateTime', 'children'])

    conn = pymysql.connect(
        host='localhost',  # 我的IP地址
        port=3306,  # 不是字符串不需要加引号。
        user='root',
        password='123456',
        db='test',
        charset='utf8'
    )

    cursor = conn.cursor()  # 获取一个光标
    confirmed_total = 0
    suspected_total = 0
    dead_total = 0
    healed_total = 0
    id = 0;
    for dict in countryname_list:
        sql = 'insert into yiqing_world (countryname,confirmed,suspected,dead,healed,lastUpdateTime,id) values (%s,%s,%s,%s,%s,%s,%s);'
        countryname = dict['name']

        confirmed = dict['total']['confirm']
        confirmed_total += confirmed
        suspected = dict['total']['suspect']
        suspected_total += suspected
        healed = dict['total']['heal']
        dead_total += healed
        dead = dict['total']['dead']
        dead_total += dead
        lastUpdateTime = dict['lastUpdateTime']
        id=id+1
        sys.stdout.write( dict['name'] + '  ')
        cursor.execute(sql, [countryname,confirmed,suspected,dead,healed,lastUpdateTime,id])
    print()

    conn.commit()


    cursor.close()
    conn.close()

 

MainActivity.java:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends Activity {

    private EditText et_name;
    private Button btn_get_data;
    private TextView tv_data;
    private RadioGroup rg_check;
    private RadioButton rb_date;
    private RadioButton rb_country;
    private String condition;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case 0x11:
                    String s = (String) msg.obj;
                    tv_data.setText(s);
                    break;
                case 0x12:
                    String ss = (String) msg.obj;
                    tv_data.setText(ss);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 控件的初始化
        btn_get_data = findViewById(R.id.btn_get_data);
        tv_data = findViewById(R.id.tv_data);
        et_name = findViewById(R.id.et_name);
        rb_date = findViewById(R.id.rb_date);
        rb_country = findViewById(R.id.rb_country);
        rg_check = findViewById(R.id.rg_select);


        rg_check.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //如果‘时间’这个单选按钮被选中了
                if(rb_date.getId()==checkedId){
                    //弹出吐司通知
                    //Toast.makeText(MainActivity.this, rb_date.getText().toString(), Toast.LENGTH_LONG).show();
                    //获取选中按钮对应的文本信息
                    condition = rb_date.getText().toString().trim();
                }else if(rb_country.getId()==checkedId){
                    //Toast.makeText(MainActivity.this, rb_country.getText().toString(), Toast.LENGTH_LONG).show();
                    condition = rb_country.getText().toString().trim();
                }
            }
        });
        //如果没有选择默认按时间查询
        if (condition == null){
            condition = rb_date.getText().toString().trim();
        }
        setListener();
    }

    /**
     * 设置监听
     */
    private void setListener() {

        // 按钮点击事件
        btn_get_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 创建一个线程来连接数据库并获取数据库中对应表的数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String name = et_name.getText().toString().trim();
                        //调用数据库帮助类中的方法取数据
                        List<information> list = DBUtils.search(condition,name);
                        Message message = handler.obtainMessage();
                        if (list != null) {
                            String s = "";
                            for (int i = 0; i < list.size(); i++) {
                                s += "国家:" + list.get(i).getCountryname() + "\n";
                                s += "最新更新时间:" + list.get(i).getLastUpdateTime() + "\n";
                                s += "确诊人数为:  " + list.get(i).getConfirmed() + "\n";
                                s += "治愈人数为:  " + list.get(i).getHealed() + "\n";
                                s += "死亡人数为:  " + list.get(i).getDead() + "\n" + "\n";
                            }
                            //0x11、0x12消息的定位标志
                            message.what = 0x12;
                            message.obj = s;
                        } else {
                            message.what = 0x11;
                            message.obj = "查询结果为空";
                        }
                        handler.sendMessage(message);

                        // 发消息通知主线程更新UI
                    }
                }).start();
            }
        });

     }

}
View Code

相关文章:

  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
  • 2021-12-02
相关资源
相似解决方案