python获取全国城市pm2.5、臭氧等空气质量过程解析

所属分类: 脚本专栏 / python 阅读数: 1990
收藏 0 赞 0 分享

随着国家发展,中国很多城市的空气质量其实并不好,国家气象局会有实时统计,但是要去写爬虫爬取是十分麻烦的事情,并且官方网站也会做一些反爬虫措施,所以实现起来比较麻烦,最好的办法就是使用现成的免费接口,空气质量指数分析,这里是笔者自己实现的一个python调用方式

代码如下:

# -*- coding: utf-8 -*-
# flake8: noqa
__author__ = 'wukong'

import urllib
from urllib import urlencode

#配置您申请的appKey和openId
app_key="***"
open_id="***"

"""
request_url 请求地址
params 请求参数
method 请求方法

"""
def request_content(request_url,params,method):
 params = urlencode(params)
 
 if method and method.lower() =="get":
  f = urllib.urlopen("%s?%s" % (request_url, params))
 else:
  f = urllib.urlopen(request_url, params)
 
 content = f.read()
 print content

 
def main():
 
 domain="http://api.xiaocongjisuan.com/";
 servlet="life/air/analysis"
 method="get"
 request_url=domain+servlet
 
 #字典
 params ={}
 params["appKey"]=app_key
 params["openId"]=open_id
 
 #变动部分
 params["city"]="成都"
 
 request_content(request_url,params,method)
 
if __name__ == '__main__':
 main()

java版的代码可以参考如下代码:

package com.xiaocongjisuan.module.example;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class Application {
 
  public static final String DEF_CHATSET = "UTF-8";
  public static final int DEF_CONN_TIMEOUT = 30000;
  public static final int DEF_READ_TIMEOUT = 30000;
  public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
  
  //配置您申请的appKey和openId
  public static final String APP_KEY ="yours";
  public static final String OPEN_ID ="yours";
  
  //将map型转为请求参数型
  public static String urlEncode(Map<String,Object> params) {
  
  if(params==null){return "";};
   
  StringBuilder sb = new StringBuilder();
  for (Map.Entry<String,Object> i : params.entrySet()) {
   try {
    sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   }
  }
  String r=sb.toString();
  if(r.endsWith("&")){
   r = r.substring(0,r.length()-1);
  }
  return r;
  }
  
  /**
  *
  * @param requestUrl 请求地址
  * @param params 请求参数
  * @param method 请求方法
  * @return 请求结果
  * @throws Exception
  */
  public static String requestContent(String requestUrl, Map<String,Object> params,String method) throws Exception {
  
  HttpURLConnection conn = null;
  BufferedReader reader = null;
  String rs = null;
  try {

   //组装请求链接
   StringBuffer sb = new StringBuffer();
   
   if(method!=null&&method.equalsIgnoreCase("get")){
    requestUrl = requestUrl+"?"+urlEncode(params);
   }

   //默认get
   URL url = new URL(requestUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   
   if(method!=null&&method.equalsIgnoreCase("post")){
     conn.setRequestMethod("POST");
     conn.setDoOutput(true);
     conn.setDoInput(true);
   }

   //参数配置
   conn.setRequestProperty("User-agent", userAgent);
   conn.setUseCaches(false);
   conn.setConnectTimeout(DEF_CONN_TIMEOUT);
   conn.setReadTimeout(DEF_READ_TIMEOUT);
   conn.setInstanceFollowRedirects(false);
   conn.connect();
   
   if (params!= null && method.equalsIgnoreCase("post")) {
    try {
     DataOutputStream out = new DataOutputStream(conn.getOutputStream());
     out.writeBytes(urlEncode(params));
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
   
   //读取数据
   InputStream is = conn.getInputStream();
   reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
   String strRead = null;
   while ((strRead = reader.readLine()) != null) {
    sb.append(strRead);
   }
   rs = sb.toString();
   
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (reader != null) {
    reader.close();
   }
   if (conn != null) {
    conn.disconnect();
   }
  }
  return rs;
 }
 
 
 public static void main(String[] args) throws Exception{
  
  String domain="http://api.xiaocongjisuan.com/";
  String servlet="life/air/analysis";
  String method="get";
  
  String requestUrl=domain+servlet;
  Map<String,Object> params=new HashMap<String,Object>();
  params.put("appKey",APP_KEY);
  params.put("openId",OPEN_ID);

  //变动部分
  params.put("city","成都");
  
  
  String result=requestContent(requestUrl,params,method);
  System.out.println(result);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Python常见加密模块用法分析【MD5,sha,crypt模块】

这篇文章主要介绍了Python常见加密模块用法,结合实例形式较为详细的分析了MD5,sha与crypt模块加密的相关实现方法与操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python向日志输出中添加上下文信息

这篇文章主要介绍了Python向日志输出中添加上下文信息的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现的简单dns查询功能示例

这篇文章主要介绍了Python实现的简单dns查询功能,结合实例形式分析了Python基于socket模块的dns信息查询实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

利用Anaconda完美解决Python 2与python 3的共存问题

Anaconda 是 Python 的一个发行版,如果把 Python 比作 Linux,那么 Anancoda 就是 CentOS 或者 Ubuntu,下面这篇文章主要给大家介绍了利用Anaconda完美解决Python 2与python 3共存问题的相关资料,文中介绍的非常详
收藏 0 赞 0 分享

Python随机读取文件实现实例

这篇文章主要介绍了Python随机读取文件的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

用生成器来改写直接返回列表的函数方法

下面小编就为大家带来一篇用生成器来改写直接返回列表的函数方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python爬虫入门教程--快速理解HTTP协议(一)

http协议是互联网里面最重要,最基础的协议之一,我们的爬虫需要经常和http协议打交道。下面这篇文章主要给大家介绍了关于python爬虫入门之快速理解HTTP协议的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

老生常谈Python进阶之装饰器

下面小编就为大家带来一篇老生常谈Python进阶之装饰器。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈Python基础之I/O模型

下面小编就为大家带来一篇浅谈Python基础之I/O模型。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python如何获取服务器硬件信息

这篇文章主要为大家详细介绍了python获取服务器硬件信息的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多