ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python-爬虫抓取天气信息

2021-07-12 16:58:55  阅读:223  来源: 互联网

标签:weatherData Python 爬虫 抓取 json weather dict logInfo data


上周

砖家预测西安在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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有