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()

抓取截图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值