天气预报首先需要的就是天气信息,可以从中国天气网的Wap网站上获取,因为Wap网站页面简单,便于抓取内容。网址是:http://wap.weather.com.cn/wap/,默认是北京的天气预报,可以更换城市。某城市的天气预报对应的网址是http://wap.weather.com.cn/wap/weather/city_code.shtml,其中city_code是城市代码。以南京市为例,南京的城市代码是101190101,所以对应的天气预报网址就是http://wap.weather.com.cn/wap/weather/101190101.shtml。
为了抓取我们需要的天气的信息,首先需要获取天气预报页面源代码,这可以使用urllib模块的urlopen方法打开页面源文件并返回一个类文件对象,然后可以通过read方法读取其内容,也就是页面源代码。
from urllib import urlopen
src_code=urlopen('http://wap.weather.com.cn/wap/weather/101190101.shtml').read() #获取页面源代码
获取的页面源代码是HTML代码,截取其中我们需要的部分内容如下:
<title>南京天气预报</title>
......
<h2><strong>南京天气预报</strong></h2>
<h3>2011-11-22 18时发布</h3>
......
<dd>11月23日星期三<br /> <img src="http://www.weather.com.cn/m/i/icon_weather/21x15/n01.gif" /><img src="http://www.weather.com.cn/m/i/icon_weather/21x15/d00.gif" /></dd>
<dt> 多云转晴6℃/12℃<br /> 北风4-5级</dt>
</dl>
<dl >
......
</body>
</html>
我们需要的内容为(当然,是不含HTML标记符号的):
1.城市名称:<title>南京天气预报</title>
2.发布时间:<h3>2011-11-22 18时发布</h3>
3.日期信息:<dd>11月23日星期三<br /> .....</dd>
4.天气信息:<dt> 多云转晴6℃/12℃<br /> 北风4-5级</dt>
提取这些信息有两种方法,一是利用强大的正则表达式,二是使用Beautiful Soup这个小模块。接下来让我们依次来实现这两种方法。
先说方法一,使用正则表达式。关于正则表达式,篇幅有限我就不多介绍了,只说如何实现我们的需求。使用正则表达式的关键是设计出合适的正则表达式。为了提取我们需要的4项内容,我们需要4个正则式。能够实现这4种匹配的正则式并不是唯一的,以下是我设计的4个正则式:
title_re = re.compile('<title>(.*)</title>') #匹配标题的正则式
release_re = re.compile('<h3>(.*)</h3>') #匹配发布时间的正则式
days_re = re.compile('<dd>(.*)<br') #匹配日期的正则式
weather_re = re.compile('<dt>(.*)<br /> (.*)</dt>') #匹配天气的正则式
re.compile(regex)返回一个正则表达式对象。使用该对象的findall(pattern,string,flag=0)方法可以返回所有匹配部分的列表。当正则表达式仅有一个子组时,findall()返回子组匹配的字符串组成的列表;如果表达式有多个子组,返回的结果是一个元组的列表,元组中每个元素都是一个子组的匹配内容。子组就是正则表达式中使用圆括号括起来的部分,在上面4个正则式中都是(.*)。
weather_title = title_re.findall(text)[0] #获取标题
release_time = release_re.findall(text)[0] #获取发布时间
days = []
for day in days_re.findall(text): #匹配日期,返回一个列表
days.append(day)
day_weather = []
for temp,wind in weather_re.findall(text): #匹配天气情况,返回一个列表
day_weather.append(temp + ',' + wind)
至此,我们就提取出了我们需要的所有内容。下面看一下完整的程序。
#! /usr/bin/env python
#coding=utf-8
from urllib import urlopen
import re #正则表达式模块
import sys #这三行设置默认编码格式为UTF-8
reload(sys) #不设置的话,使用不同的编译器可能
sys.setdefaultencoding('utf-8') #会出现编码错误
#这个网址是江宁天气预报,可以根据实际情况修改
my_url = 'http://wap.weather.com.cn/wap/weather/101190101.shtml'
title_re = re.compile('<title>(.*)</title>') #匹配标题的正则式
release_re = re.compile('<h3>(.*)</h3>') #匹配发布时间的正则式
days_re = re.compile('<dd>(.*)<br') #匹配日期的正则式
weather_re = re.compile('<dt>(.*)<br /> (.*)</dt>') #匹配天气的正则式
text = urlopen(my_url).read() #获取页面源代码
weather_title = title_re.findall(text)[0] #获取标题
release_time = release_re.findall(text)[0] #获取发布时间
days = []
for day in days_re.findall(text): #匹配日期,返回一个列表
days.append(day)
day_weather = []
for temp,wind in weather_re.findall(text): #匹配天气情况,返回一个列表
day_weather.append(temp + ',' + wind)
print weather_title
print release_time
for i in range(5):
print '%s' % days[i],day_weather[i]
使用正则表达式有几个缺点,一是正则表达式并不是完全可读的,二是正则表达式被HTML源代码约束,这就意味着网页结构中很小的改动就会导致程序中断。所以我们需要更好的实现方式,也就是我说的第二种方法,使用Beautiful Soup。
Beautiful Soup是个小模块,用来解析和检查HTML。关于Beautiful Soup的详细使用说明请移步http://www.crummy.com/software/BeautifulSoup/documentation.zh.html。这里只说如何实现我们的需求。
使用Beautiful Soup首先还是要获取页面源代码,然后由源代码生成soup,再使用soup的findAll方法来抽取各标签内容。下面直接放上完整程序,关键地方我都有注释。
# -*- coding: UTF-8 -*-
from BeautifulSoup import BeautifulSoup # For processing HTML
from urllib import urlopen
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Weather_Info:
"""Weather class"""
def __init__(self, site):
self.site = site
return
def get_weather(self):
"""Get the weather information from the Internet"""
text = urlopen(self.site).read() #Get the source code of the site
soup = BeautifulSoup(text) #Get the soup
weather_title = soup.title.string #获取<title>标签的内容
city_name = weather_title.strip('天气预报 ') #除于“天气预报”剩下的就是城市
release_time = soup.h3.string #获取<h3>标签的内容
print '%s' % city_name
print '%s' % release_time
days = []
for day in soup.findAll('dd'): #获取<dd>标签的内容
days.append(day.contents[0])
day_weather = []
for weather in soup.findAll('dt'): #获取<dt>标签的内容
if len(weather.contents) == 3: #含有3项内容的<dt>标签才是我们需要的(3项内容举例:' 晴3℃/14℃','<br />',' 北风4-5级转东南风3-4级')
temperature = weather.contents[0].strip() #第一项内容除去空格就是气温信息
wind = weather.contents[2].strip().replace(' ', ',') #第三项内容除去' '就是风力信息,替换成逗号便于与气温信息连接
day_weather.append(temperature + wind)
for i in range(5):
print '%s' % days[i], day_weather[i]
if __name__ == '__main__':
myWeather = Weather_Info('http://wap.weather.com.cn/wap/weather/101190101.shtml')
myWeather.get_weather()
可以看出,使用Beautiful Soup的实现方法更简单易懂。
好了,我们已经从网上获取到了天气信息,请看下一篇——
分享到:
相关推荐
天气预报信息——易语言模块 天气预报信息——易语言模块
微信小程序——天气预报(截图+源码).zip 微信小程序——天气预报(截图+源码).zip 微信小程序——天气预报(截图+源码).zip 微信小程序——天气预报(截图+源码).zip 微信小程序——天气预报(截图+源码).zip ...
人工智能技术能否提高地面气温预报的精度——记AI Challenger 2018全球天气预报挑战赛.pdf
IOS应用源码——天气预报.zip
Android开发之系统信息【3】——获取Android网络连接信息Android开发之系统信息【3】——获取Android网络连接信息
Android开发之系统信息【5】——获取APN列表Android开发之系统信息【5】——获取APN列表
Android开发之系统信息【2】——获取Android手机内存信息.docxAndroid开发之系统信息【2】——获取Android手机内存信息.docxAndroid开发之系统信息【2】——获取Android手机内存信息.docx
程序中用到的数据库,含有全国上千城市代码 博文链接:https://think3t.iteye.com/blog/1772830
Android开发之系统信息【1】——获取Android手机中SD卡存储信息Android开发之系统信息【1】——获取Android手机中SD卡存储信息
├─05 实战Google Maps API之三——地图天气预报服务 │ ├─5.1 在Google地图上显示天气预报 │ │ ├─5.1.2 利用Google AJAX Feed API加载RSS文档 │ │ └─5.1.3 YWeather()类的构造 │ └─5.2 │ └─...
安卓Android源码——天气预报源码.zip
通过调用webservice显示全国天气预报
Android开发之系统信息【4】——获取Android已安装程序列表Android开发之系统信息【4】——获取Android已安装程序列表
安卓Android源码——获取手机信息.zip
基于App Inventor积木式编程API调用的设计与实现——以天气预报APP为例.pdf
《LoadRunner没有告诉你的》之六——获取有效的性能需求
人工智能技术的热带气旋预报综述(之一)——BP神经网络和集成方法的热带气旋预报研究和业务应用.pdf
安卓Android源码——获取系统程序信息.zip
安卓Andriod源码——获取手机应用信息.zip