思路:
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() + " "; s += "最新更新时间:" + list.get(i).getLastUpdateTime() + " "; s += "确诊人数为: " + list.get(i).getConfirmed() + " "; s += "治愈人数为: " + list.get(i).getHealed() + " "; s += "死亡人数为: " + list.get(i).getDead() + " " + " "; } //0x11、0x12消息的定位标志 message.what = 0x12; message.obj = s; } else { message.what = 0x11; message.obj = "查询结果为空"; } handler.sendMessage(message); // 发消息通知主线程更新UI } }).start(); } }); } }
DBUtils.java:
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.List; /** * 数据库工具类:连接数据库用、获取数据库数据用 * 相关操作数据库的方法均可写在该类 */ public class DBUtils { private static String driver = "com.mysql.jdbc.Driver";// MySql驱动 private static String user = "root";// 用户名 private static String password = "123456";// 密码 private static Connection getConn(String dbName) { Connection connection = null; try { Class.forName(driver);// 动态加载类 String ip = "192.168.1.6";// 写成本机地址,不能写成localhost,同时手机和电脑连接的网络必须是同一个 // 尝试建立到给定数据库URL的连接 connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + dbName, user, password); } catch (Exception e) { e.printStackTrace(); } return connection; } public static List<information> search(String condition, String country_name){ List<information> list = new ArrayList<>(); Connection connection = getConn("test"); String sql = ""; //System.out.println(condition); //选择条件 if(condition.equals("国家")){ //模糊查询 sql = "select * from yiqing_world where countryname like ?"; } if(condition.equals("时间")){ sql = "select * from yiqing_world 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()){ information worldData = new information(); worldData.setId(rs.getInt("id")); worldData.setCountryname(rs.getString("countryname")); worldData.setConfirmed(rs.getString("confirmed")); worldData.setSuspected(rs.getString("suspected")); worldData.setDead(rs.getString("dead")); worldData.setHealed(rs.getString("healed")); worldData.setLastUpdateTime(rs.getString("lastUpdateTime")); list.add(worldData); } connection.close(); ps.close(); return list; }else{ return null; } }else{ return null; } } catch (SQLException e) { e.printStackTrace(); return null; } }else{ return null; } } }
information.java:
public class information { 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; } }
布局文件activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:padding="15dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <RadioGroup android:id="@+id/rg_select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingLeft="20dp" android:layout_marginTop="20dp"> <RadioButton android:id="@+id/rb_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="时间" android:textSize="20sp" android:checked="true"/> <RadioButton android:id="@+id/rb_country" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="国家" android:textSize="20sp"/> </RadioGroup> <EditText android:id="@+id/et_name" android:padding="10dp" android:textSize="16sp" android:gravity="center" android:hint="输入要查询的内容" android:layout_below="@id/rg_select" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_get_data" android:layout_margin="15dp" android:textSize="16sp" android:text="查询" android:layout_below="@id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_data" android:padding="10dp" android:textSize="16sp" android:gravity="center" android:text="内容" android:layout_below="@+id/btn_get_data" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> </ScrollView>
运行截图: