python获取全国各个城市pm2.5、臭氧等空气质量
随着国家发展,中国很多城市的空气质量其实并不好,国家气象局会有实时统计,但是要去写爬虫爬取是十分麻烦的事情,并且官方网站也会做一些反爬虫措施,所以实现起来比较麻烦,最好的办法就是使用现成的免费接口,空气质量指数分析,这里是笔者自己实现的一个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获取全国各个城市pm2.5、臭氧等空气质量的更多相关文章
- Java处理文件小例子--获取全国所有城市的坐标
需求:前端展示数据,全国城市的坐标
- Python爬网获取全国各地律师电话号
[本文出自天外归云的博客园] 从64365网站获取全国各地律师电话号,用到了python的lxml库进行对html页面内容的解析,对于xpath的获取和正确性校验,需要在火狐浏览器安装firebug和 ...
- python获取公网ip,本地ip及所在国家城市等相关信息收藏
python获取公网ip的几种方式 from urllib2 import urlopen my_ip = urlopen('http://ip.42.pl/raw').read() ...
- 用python+selenium获取北上广深成五地PM2.5数据信息并按空气质量排序
从http://www.pm25.com/shenzhen.html抓取北京,深圳,上海,广州,成都的pm2.5指数,并按照空气质量从优到差排序,保存在txt文档里 代码如下: #coding=utf ...
- 全国城市空气质量实时数据(PM2.5)实时下载
国家公布了“http://113.108.142.147:20035/emcpublish/”空气质量实时发布平台,WCF服务地址为“http://113.108.142.147:20035/EnvP ...
- 天气类API调用的代码示例合集:全国天气预报、实时空气质量数据查询、PM2.5空气质量指数等
以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 全国天气预报:数据来自国家气象局,可根据地名.经纬度GPS.IP查 ...
- 获取全国市以及地理坐标,各大坐标系北斗,百度,WGS-84坐标系的转换,有图,有代码
1 先上坐标取到的值: 获取到的坐标部分如下: '北京市':[116.39564503788,39.92998577808], '天津市':[117.21081309155,39.1439299033 ...
- LetterView实现载入全国各地城市
近期更具eoe论坛上的letteView案例( eoe)自己做了一个LetterView载入全国城市的案例,欢迎大家互相学习和交流, 相对于eoe那个案例稍微修改了一下,利用json存储全国城市数 ...
- Jsoup获取全国地区数据(省市县镇村)
最近手头在做一些东西,需要一个全国各地的地域数据,从省市区到县镇乡街道的.各种度娘,各种谷歌,都没找到一个完整的数据.最后功夫不负有心人,总算找到一份相对来说比较完整的数据,但是这里的数据也只是精确到 ...
随机推荐
- HYSBZ - 4016 最短路径树问题 点分治 + 最短路径最小字典序
题目传送门 题解:首先对于给定的图,需要找到那些从1好点出发然后到x号点的最短路, 如果有多条最短路就要找到字典序最小的路,这样扣完这些边之后就会有一棵树.然后再就是很普通的点分治了. 对于扣边这个问 ...
- codeforces 743D. Chloe and pleasant prizes(树形dp)
题目链接:http://codeforces.com/contest/743/problem/D 大致思路挺简单的就是找到一个父节点然后再找到其两个字节点总值的最大值. 可以设一个dp[x]表示x节点 ...
- 如何将idea工程打包成jar文件
如何将idea工程打包成jar文件 近日在工作中遇到了一个问题,需要把本地的java文件打成jar包,传到云服务器上运行.于是学习了一下如何在intellij idea中将java工程打成jar包. ...
- Three.js 开发机房(三)
之前三节都没涉及到机房,只是一些零零散散的知识点,这一节我们就开始正式画外墙. 首先我了明显理解以下啥是墙?其实说白了就是一个长方体,长不确定,宽一般也就是40cm,高也就是两米,这就是一个简单的墙, ...
- 2018阿里前端 - 认真写下阿里的面筋,祝福大家收到满意的offer(前端向)
作者:叮!阿里offer请查收!链接:https://www.nowcoder.com/discuss/102509来源:牛客网 首先表达一下对阿里面试官的感谢,以及大公司的气魄——没有因为不是科班出 ...
- CXF添加拦截器和自定义拦截器
前面讲了如何采用CXF开发webservice,现在来讲如何添加拦截器和自定义拦截器. 服务端代码: HelloWorld implementor=new HelloWorldImpl(); Stri ...
- .Net基础篇_学习笔记_第三天_Convert类型转换
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- thymeleaf+layui加载页面渲染时TemplateProcessingException: Could not parse as expression
Caused by: org.attoparser.ParseException: Could not parse as expression: " {type: 'numbers'}, { ...
- python time.striptime模块用法
python time模块中strptime用法 time.strptime(string[, format]) 其中string参数即为要深入的日期字符串.format为格式化的日期字符串. %Y ...
- Spring Boot 入门之整合 log4jdbc 篇(六)
博客地址:http://www.moonxy.com 一.前言 Spring Data JPA 默认采用 Hibernate 实现.Hibernate 的 showSql 配置只打印 SQL,但并不打 ...