编程语言
首页 > 编程语言> > Python-爬虫抓取天气信息

Python-爬虫抓取天气信息

作者:互联网

上周

砖家预测西安在10-11日

会有一场十年不遇的大雨

像我这样优秀的人

必须得提醒大家

于是

我提前三四天开始给大家预热

然而

除了我的眼泪

就没有更大的雨滴

所以我暗下决心

我命由我不由天

在这炎热的夏季

我的命就是空调、冰箱、大西瓜

火腿、花生、八宝粥

啤酒、饮料、矿泉水

咳咳

当然还有天气预报

分析:

1、毫无分析可言,代码也就十来行

翠花,上酸菜

1、使用链接和城市名拼接,可以获取该城市天气信息

http://wthrcdn.etouch.cn/weather_mini?city=西安

2、抓取的数据是json格式,可以直接用json解析

源码:

# -*- encoding:utf8 -*-

import json
import requests
import re


WEATHER_URL    = "http://wthrcdn.etouch.cn/weather_mini?city="

def GetWeatherInfo(cityName) :
    weatherJsonUrl = WEATHER_URL + cityName
    response = requests.get(weatherJsonUrl)  # 获取并下载页面,其内容会保存在respons.text里
    response.raise_for_status()  # 请求失败的话就会抛出异常

    # 将json文件格式导入成python的格式
    weatherData = json.loads(response.text)
    #print(weatherData)

    weather_dict = dict()
    weather_dict['type'] = weatherData['data']['forecast'][0]['type']
    weather_dict['high'] = weatherData['data']['forecast'][0]['high']
    weather_dict['low'] = weatherData['data']['forecast'][0]['low']
    weather_dict['fengxiang'] = weatherData['data']['forecast'][0]['fengxiang']
    weather_dict['ganmao'] = weatherData['data']['ganmao']

    logInfo = cityName + ": "
    for i, value in enumerate(weather_dict.values()) :
        logInfo += value
        if i < len(weather_dict.values())-1 :
            logInfo += ", "
        else :
            logInfo += "\n"
    print(logInfo)
	
def main() :
    GetWeatherInfo('西安')

main()

抓取截图:

 

标签:weatherData,Python,爬虫,抓取,json,weather,dict,logInfo,data
来源: https://blog.csdn.net/zhanglu_1024/article/details/118678786