Python爬取天气实况(1)

一、最初的想法

我们昨天弄了个爬取天气实况的程序,本文章用以记录思考和编写过程。
这里选取的爬取网站是http://q-weather.info/weather/59488//realtime/
下图就是查天气网站截图。
(站号修改成其他气象站号就可以查询其他城市的实况)
查天气网站
我们以59488珠海站为例,爬取的HTML源代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN">\n<head>\n\t<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />\n\t<title>查天气</title>\n\t<style type="text/css">\n\t\ttable {\n\t\t\tborder-width: 0px;\n\t\t\tborder-style: solid;\n\t\t\tborder-collapse: collapse;\n\t\t}\n\t\ttable th {\n\t\t\tborder-width: 1px;\n\t\t\tpadding: 3px;\n\t\t\tborder-style: solid;\n\t\t}\n\t\ttable td {\n\t\t\tborder-width: 1px;\n\t\t\tpadding: 3px;\n\t\t\tborder-style: solid;\n\t\t}\n\t</style>\n</head>\n<body>\n\t<center>\n\t\t<h1>59488 (珠海) 站的当前实况</h1>\n\t\t<table>\n\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>气象要素</th>\n\t\t\t\t\t<th>值</th>\n\t\t\t\t\t<th>更新时间</th>\n\t\t\t\t</tr>\n\t\t\t</thead>\n\t\t\t<tbody>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>瞬时温度</td>\n\t\t\t\t\t<td>24.4</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>24小时变温</td>\n\t\t\t\t\t<td>-3.7</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>地面气压</td>\n\t\t\t\t\t<td>1004.2</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>相对湿度</td>\n\t\t\t\t\t<td>97</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>10分钟平均风向</td>\n\t\t\t\t\t<td>WNW</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>10分钟平均风速</td>\n\t\t\t\t\t<td>2.0</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>1小时降水</td>\n\t\t\t\t\t<td>0.1</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>24小时降水</td>\n\t\t\t\t\t<td>40.4</td>\n\t\t\t\t\t<td>2020-05-10 20:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr align="center">\n\t\t\t\t\t<td>10分钟平均能见度</td>\n\t\t\t\t\t<td>16.534</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>\n\t\t\t</tbody>\n\t\t</table>\n\t</center>\n</body>\n</html>\n

如果将转义字符转义(就是将\n和\t变成换行和制表),也就是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<title>查天气</title>
	<style type="text/css">
		table {
			border-width: 0px;
			border-style: solid;
			border-collapse: collapse;
		}
		table th {
			border-width: 1px;
			padding: 3px;
			border-style: solid;
		}
		table td {
			border-width: 1px;
			padding: 3px;
			border-style: solid;
		}
	</style>
</head>
<body>
	<center>
		<h1>59488 (珠海) 站的当前实况</h1>
		<table>
			<thead>
				<tr>
					<th>气象要素</th>
					<th>值</th>
					<th>更新时间</th>
				</tr>
			</thead>
			<tbody>
				<tr align="center">
					<td>瞬时温度</td>
					<td>24.4</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>24小时变温</td>
					<td>-3.7</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>地面气压</td>
					<td>1004.2</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>相对湿度</td>
					<td>97</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>10分钟平均风向</td>
					<td>WNW</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>10分钟平均风速</td>
					<td>2.0</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>1小时降水</td>
					<td>0.1</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
				<tr align="center">
					<td>24小时降水</td>
					<td>40.4</td>
					<td>2020-05-10 20:00 +0800</td>
				</tr>
				<tr align="center">
					<td>10分钟平均能见度</td>
					<td>16.534</td>
					<td>2020-05-10 21:00 +0800</td>
				</tr>
			</tbody>
		</table>
	</center>
</body>
</html>

我最初的想法是将每个气象要素按照名称爬下来,这也是很朴素的想法。
我先把HTML中的所有多余的标签和转义字符去掉,但不能全部去掉,因为一旦全部去掉,所有数据都连在一起,就没有办法把他们正确分开了。因此我们故意不去掉/td标签。
然后对每一个气象要素都写一个专门的正则表达式。
/td标签到最后输出的时候可以直接被替换成需要的分隔符(如“:”、“(”、“)”)。
举个例子:

<tr align="center">\n\t\t\t\t\t<td>地面气压</td>\n\t\t\t\t\t<td>1004.2</td>\n\t\t\t\t\t<td>2020-05-10 21:00 +0800</td>\n\t\t\t\t</tr>

去掉“\n\t\r、td标签、tr标签、<tr align=“center”>标签”,只留下/td标签后的效果:

地面气压</td>1004.2</td>2020-05-10 21:00 +0800</td>

最后将/td替换成需要的字符:

地面气压:1003(更新时间:2020-05-10 10:00+0800)

按照如上思路,代码如下:

import requests
import re

r = requests.get("http://q-weather.info/weather/59488/realtime/",timeout=30)
delete = re.compile(r'[\n\t\r]+|<td>|</tr>|<tr align=\"center\">')#去掉不需要的标签

html = re.sub(delete,'',r.text)

def dec(s):
#该函数作用是修整字符串,打印成格式如“瞬时温度:24.3(更新时间:2020-05-10 10:00+0800)”
    m = re.split('</td>',s)#找出每个/td,分离字符串
    print(m[0]+':'+m[1]+'(更新时间:'+m[2]+')')

pat = re.compile(r'\d{5}.*站的当前实况')#提取标题
temp = pat.search(html).group(0)
print(temp)
#下面的都是提取各个气象要素,然后送去修整字符串的函数处理
pat = re.compile(r'瞬时温度</td>.*?</td>.*?</td>')#对每一个气象要素都写个正则表达式
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'24小时变温</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'地面气压</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'相对湿度</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'10分钟平均风向</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'10分钟平均风速</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'1小时降水</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'24小时降水</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

pat = re.compile(r'10分钟平均能见度</td>.*?</td>.*?</td>')
temp = pat.search(html).group(0)
dec(temp)

这段程序输出没有什么问题,一切都如计划中进行,然而有时候却会出现匹配失败的信息,这又是怎么回事呢?
原来有时候随着网站更新数据,气象要素的名称不是一成不变的,有时候不是“10分钟平均风速”,而是“瞬时风速”,有时候不是“10分钟平均风向”,而是“瞬时风向”,这样就匹配不了了。

二、进一步改进

分析了以上情况后,以上的这个代码就不可行了,这说明正则表达式中不能直接出现气象要素名称。
观察下面的HTML源代码,可以发现每一组气象数据都包含在tr标签里面,所以正则表达式是:

"<tr align=\"center\">.*?</tr>"

用findall函数遍历整个HTML源码,遍历结果写入一个列表中,然后将遍历结果中多余的标签和换行字符用re库的sub函数全部去掉。
然而我们发现以上的表达式仍然不能匹配出任何有效信息,列表是空的,这是为什么呢?我专门去搜索了一下原因。
原来,.是匹配除过\n 之外的全部字符,用[\d\D] 匹配所有字符,或者用[\s\S] 也可以。
所以正则表达式进一步改成:

"<tr align=\"center\">[\d\D]*?</tr>"

最后的核心代码如下:

import requests
import re

r = requests.get("http://q-weather.info/weather/59488/realtime/", timeout=30)

pat_title = re.compile(r'\d{5}.*站的当前实况')#提取标题
title = pat_title.search(r.text).group(0)
print(title)

lst = re.findall(r'<tr align=\"center\">[\d\D]*?</tr>', r.text)#配对

for l in lst:
    m = re.sub(r'[\n\t]+|<td>|</tr>|<tr align=\"center\">', '', l)#删掉不要的标签
    result = re.split('</td>',m)#分离字符串
    print(result[0]+':'+result[1]+' (更新时间:'+result[2]+')')

可以看到代码长度一下减少了很多。
输出结果如下:

59488 (珠海) 站的当前实况
瞬时温度:30.1 (更新时间:2020-05-11 09:40 +0800)
24小时变温:0.2 (更新时间:2020-05-11 09:40 +0800)
地面气压:1006.3 (更新时间:2020-05-11 09:40 +0800)
相对湿度:68 (更新时间:2020-05-11 09:40 +0800)
10分钟平均风向:ENE (更新时间:2020-05-11 09:40 +0800)
10分钟平均风速:3.3 (更新时间:2020-05-11 09:40 +0800)
1小时降水:0.0 (更新时间:2020-05-11 09:00 +0800)
24小时降水:40.5 (更新时间:2020-05-11 09:00 +0800)
10分钟平均能见度:30.000 (更新时间:2020-05-11 09:00 +0800)

当然这只是个初步的代码,许多异常情况未考虑进去,比如气象站号不存在、爬虫过程中出现请求失败等情况,仍然有改进之处。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
天气查询APP,两种JSON解析方式 /** * 原始json数据解析 * */ // JSONObject jsonObject = new JSONObject(res); // String reason=jsonObject.getString("reason"); // if (reason.equals("参数不正确")){ // handler.sendEmptyMessage(1); // return; // } // JSONObject result=jsonObject.getJSONObject("result"); // JSONObject realtime=result.getJSONObject("realtime"); // JSONObject life=result.getJSONObject("life"); // JSONObject wind=realtime.getJSONObject("wind"); // String time=realtime.getString("time"); // JSONObject weather=realtime.getJSONObject("weather"); // String date=realtime.getString("date"); // dateStr=time+date; // weekStr=realtime.getString("week"); // calendarStr=realtime.getString("moon"); // windpowerStr=wind.getString("direct")+" "+wind.getString("power"); // weatherStr=weather.getString("info"); // temperatureStr=weather.getString("temperature"); // JSONObject info=life.getJSONObject("info"); // JSONArray kongtiao=info.getJSONArray("kongtiao"); // JSONArray yundong=info.getJSONArray("yundong"); // JSONArray ziwaixian=info.getJSONArray("ziwaixian"); // ACStr=kongtiao.getString(0)+" "+kongtiao.getString(1); // sportStr=yundong.getString(0)+" "+yundong.getString(1); // lightStr=ziwaixian.getString(0)+" "+ziwaixian.getString(1); /** * Gson数据解析 */ WheatherBean wheatherBean=new Gson().fromJson(res,WheatherBean.class); String reason=wheatherBean.getReason(); if (reason.equals("参数不正确")){ handler.sendEmptyMessage(1); return; } WheatherBean.ResultBean resultBean=wheatherBean.getResult(); WheatherBean.ResultBean.RealtimeBean realtimeBean=resultBean.getRealtime(); WheatherBean.ResultBean.RealtimeBean.WindBean windBean=realtimeBean.getWind(); String time=realtimeBean.getTime(); WheatherBean.ResultBean.RealtimeBean.WeatherBean weatherBean=realtimeBean.getWeather(); String date=realtimeBean.getDate(); dateStr=time+date; weekStr=realtimeBean.getWeek(); calendarStr=realtimeBean.getMoon(); windpowerStr=windBean.getDirect()+" "+windBean.getPower(); temperatureStr=weatherBean.getTemperature(); weatherStr=weatherBean.getInfo(); WheatherBean.ResultBean.LifeBean lifeBean=resultBean.getLife(); WheatherBean.ResultBean.LifeBean.InfoBean infoBean=lifeBean.getInfo(); List<String> kongtiao=infoBean.getKongtiao(); List<String> yundong=infoBean.getYundong(); List<String> ziwaixian=infoBean.getZiwaixian(); ACStr=kongtiao.get(0)+" "+kongtiao.get(1); sportStr=yundong.get(0)+" "+yundong.get(1); lightStr=ziwaixian.get(0)+" "+ziwaixian.get(1); }
要使用Python爬取天气信息,可以使用第三方库如requests和BeautifulSoup来获取和解析网页内容。首先,使用requests库发送HTTP请求获取网页的HTML代码。然后,使用BeautifulSoup库对HTML代码进行解析,提取所需的天气信息。 引用中提到了使用requests和BeautifulSoup来爬取网页数据的示例代码。在该示例中,使用了`requests.get()`方法获取网页内容,然后使用BeautifulSoup来解析HTML代码并提取所需的天气信息。 引用中提到了一个HtmlParser类,它使用BeautifulSoup来解析给定的HTML代码,并从中提取天气信息。在该示例中,使用了`find()`和`find_all()`方法来查找指定的HTML元素,并使用`.string`属性获取元素的文本内容。 引用中还提到了一个DataStorage类,它使用pandas库来存储天气数据。在该示例中,使用了`DataFrame()`方法创建一个数据框,并使用`.to_csv()`方法将数据保存到CSV文件中。 综上所述,要使用Python爬取天气信息,需要使用requests库发送HTTP请求获取网页内容,然后使用BeautifulSoup来解析HTML代码并提取所需的信息,最后使用pandas库将数据存储到文件中。根据引用和引用中的示例代码,你可以参考这些示例来实现你的爬取天气信息的代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python爬取天气数据,并且进行天气预报(已实现)](https://blog.csdn.net/qq_50847752/article/details/127884116)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【Python】实现爬虫(完整版),爬取天气数据并进行可视化分析](https://blog.csdn.net/chandfy/article/details/125153243)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值