查天气(1)

http://wthrcdn.etouch.cn/weather_mini?citykey=101280804

http://wthrcdn.etouch.cn/WeatherApi?citykey=101280804

http://bbs.crossincode.com/forum.php?mod=viewthread&tid=8&extra=page%3D4 

http://bbs.crossincode.com/forum.php?mod=viewthread&tid=9&extra=page%3D4


查天气(2)

# -*- coding: utf-8 -*-
import urllib2
web = urllib2.urlopen('http://www.baidu.com')
content = web.read()
print content

# -*- coding: UTF-8 -*-
import urllib2
import json
from city import city
cityname = raw_input('你想查哪个城市的天气?\n')
citycode = city.get(cityname)
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
content = urllib2.urlopen(url).read()
print content

http://www.weather.com.cn/data/cityinfo/101280800.html

# -*- coding: UTF-8 -*-
import urllib2
import json
from city import city cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
citycode = city.get(cityname.decode('gbk').encode('utf-8'))
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
print url
content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
print content

查天气(3)

看一下我们已经拿到的json格式的天气数据:

{"weatherinfo":{"city":"佛山","cityid":"101280800","temp1":"14℃","temp2":"24℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}
{
"weatherinfo":{
"city":"佛山",
"cityid":"101280800",
"temp1":"14℃",
"temp2":"24℃",
"weather":"晴",
"img1":"n0.gif",
"img2":"d0.gif",
"ptime":"18:00"}
}

直接在命令行中看到的应该是没有换行和空格的一长串字符,这里我把格式整理了一下。可以看出,它像是一个字典的结构,但是有两层。最外层只有一个key--“weatherinfo”,它的value是另一个字典,里面包含了好几项天气信息,现在我们最关心的就是其中的temp1,temp2和weather。

虽然看上去像字典,但它对于程序来说,仍然是一个字符串,只不过是一个满足json格式的字符串。我们用python中提供的另一个模块json提供的loads方法,把它转成一个真正的字典。

import json
data = json.loads(content)

这时候的data已经是一个字典,尽管在控制台中输出它,看上去和content没什么区别,只是编码上有些不同:

{u'weatherinfo': {u'city': u'\u4f5b\u5c71', u'ptime': u'18:00', u'cityid': u'101280800', u'temp2': u'24\u2103', u'temp1': u'14\u2103', u'weather': u'\u6674', u'img2': u'd0.gif', u'img1': u'n0.gif'}}

但如果你用type方法看一下它们的类型:

        print type(content)
print type(data)

就知道区别在哪里了。

# -*- coding: UTF-8 -*-
import urllib2
import json
from city import city cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
print
citycode = city.get(cityname.decode('gbk').encode('utf-8'))
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
print url
content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
content1 = urllib2.urlopen(url).read()
data = json.loads(content1)
print type(content)
print type(data)
print data
print content

之后的事情就比较容易了。

        result = data['weatherinfo']
str_temp = ('%s\n%s ~ %s') % (
result['weather'],
result['temp1'],
result['temp2'] )
print str_temp

# -*- coding: UTF-8 -*-
import urllib2
import json
from city import city cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
print
citycode = city.get(cityname.decode('gbk').encode('utf-8'))
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
print url
content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
content1 = urllib2.urlopen(url).read()
data = json.loads(content1)
print type(content)
print type(data)
print data
print content
result = data['weatherinfo']
str_temp = ('%s\n%s ~ %s') % (
result['weather'],
result['temp1'],
result['temp2'] )
print str_temp

为了防止在请求过程中出错,我加上了一个异常处理。

try:
###
###
except:
print '查询失败'

以及没有找到城市时的处理:

if citycode:
###
###
else:
print '没有找到该城市'
# -*- coding: UTF-8 -*-
import urllib2
import json
from city import city cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
citycode = city.get(cityname.decode('gbk').encode('utf-8'))
if citycode:
try:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
print url
content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
content1 = urllib2.urlopen(url).read()
data = json.loads(content1)
print type(content)
print type(data)
print data
print content
result = data['weatherinfo']
print result
str_temp = ('%s\n%s ~ %s') % (
result['weather'],
result['temp1'],
result['temp2'] )
print str_temp
except:
print '查询失败'
else:
print '没有找到该城市'


查天气(4)

这一课算是“查天气”程序的附加内容。没有这一课,你也查到天气了。但了解一下城市代码的抓取过程,会对网页抓取有更深的理解。

天气网的城市代码信息结构比较复杂,所有代码按层级放在了很多xml为后缀的文件中。而这些所谓的“xml”文件又不符合xml的格式规范,导致在浏览器中无法显示,给我们的抓取又多加了一点难度。

首先,抓取省份的列表:

# -*- coding: UTF-8 -*-
import urllib2 url1 = 'http://m.weather.com.cn/data3/city.xml' content1 = urllib2.urlopen(url1).read() provinces = content1.split(',') print content1

输出content1可以查看全部省份代码:

对于每个省,抓取城市列表:

url = 'http://m.weather.com.cn/data3/city%s.xml'

for p in provinces:

   p_code = p.split('|')[0]

   url2 = url % p_code

   content2 = urllib2.urlopen(url2).read()

   cities = content2.split(',')

   print content2.decode('utf-8')

输出content2可以查看此省份下所有城市代码:

再对于每个城市,抓取地区列表:

   for c in cities[:3]:

        c_code = c.split('|')[0]

        url3 = url % c_code

        content3 = urllib2.urlopen(url3).read()

        districts = content3.split(',')

        print content3.decode('utf-8')

content3是此城市下所有地区代码:

最后,对于每个地区,我们把它的名字记录下来,然后再发送一次请求,得到它的最终代码:

Python入门 来点栗子的更多相关文章

  1. python入门之小栗子

    1 点球小游戏: from random import choice score=[0,0]direction=['left','center','right'] def kick(): print ...

  2. PYTHON 学习笔记1 PYTHON 入门 搭建环境与基本类型

    简介 Python,当然大家听到这个名词不再是有关于像JAVA 一样的关于后台,我们学习Python 的目的在于对于以后数据分析和机器学习AI 奠定基础,Python 在数据分析这一块,可谓是有较好的 ...

  3. python入门简介

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  4. python入门学习课程推荐

    最近在学习自动化,学习过程中,越来越发现coding能力的重要性,不会coding,基本不能开展自动化测试(自动化工具只是辅助). 故:痛定思痛,先花2个星期将python基础知识学习后,再进入自动化 ...

  5. Python运算符,python入门到精通[五]

    运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...

  6. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

  7. Python基本语法,python入门到精通[二]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...

  8. visual studio 2015 搭建python开发环境,python入门到精通[三]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]很多园友提到希望使用visual studio 2013/visual studio 2015 python做demo, ...

  9. python入门教程链接

    python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...

随机推荐

  1. [Windows Server 2008] Serv-U安全设置

    ★ 欢迎来到[护卫神·V课堂],网站地址:http://v.huweishen.com ★ 护卫神·V课堂 是护卫神旗下专业提供服务器教学视频的网站,每周更新视频. ★ 本节我们将带领大家:Serv- ...

  2. 【译】x86程序员手册04 - 2.2数据类型

    2.2 Data Types 数据类型 Bytes, words, and doublewords are the fundamental data types (refer to Figure 2- ...

  3. =new、=null、.clear()、system.gc()的区别

    开发经验告诉我 = new是指向另一个地址空间 =null对象被回收 .clear()对象被清空,但是仍然指向原来的地址空间 这三种方式都并没有真正的清理内存 只有system.gc()是直接清理,但 ...

  4. MFC CAD控制权问题

    begineditorcommand(); 隐藏对话框  把控制权交给CAD completeeditorcommand(); 完成交互返回到应用程序 canceleditorcommand CAD被 ...

  5. 关于panda中dataframe的与&运算*(stackoverflow高票答案)

    85 down vote favorite 31 What explains the difference in behavior of boolean and bitwise operations ...

  6. P1638 逛画展

    题目描述 博览馆正在展出由世上最佳的 M 位画家所画的图画. wangjy想到博览馆去看这几位大师的作品. 可是,那里的博览馆有一个很奇怪的规定,就是在购买门票时必须说明两个数字, a和b,代表他要看 ...

  7. [CodeForces] 274E Mirror Room

    题意翻译 有一个n*m的格子图,其中有一些是黑色的,另一些为白色. 从某个白色格子的中心点向左上(NW),左下(SW),右上(NE),右下(SE)四个方向中的一个发出一束光线,若光线碰到黑色格子或者墙 ...

  8. Django REST framework 分页

    三种分页:根据页码.根据索引.根据加密 http://www.xx.com/courses/?page=1&size=10 http://www.xx.com/courses/?offset= ...

  9. CentOS6.8 安装python2.7,pip以及yum

    由于CentOS6.8里自带的yum所依赖的python是2.6.66版本,但是安装pip至少要求python是2.7版本,因而原有的2.6并不能卸载,又得安装新的2.7.之前安装的时候强制卸载了2. ...

  10. C#学习笔记_08_面向对象

    08_面向对象 面向对象:一种看待问题解决问题的思维方式,着眼点在于找到一个能够帮助我们解决问题的实体,然后委托这个实体来帮我们解决问题:(在面向对象之前你要有一个女朋友,否则代码会经常出现bug) ...