Python一个简单的抓取天气数据的API接口

前提安装:Python3

安装第三方库:pip3 install urllib3; pip3 install BeautifulSoup4; pip3 install bottle


import urllib.request  

import json
from bs4 import BeautifulSoup 
from bottle import route, run, request




'''
获取所有城市的空气质量数据
''' 
@route('/getCitysAirQualityData')
def getCitysAirQualityData():


    #网址  
    url = "http://www.pm25.com/rank.html"  
  
    #请求  
    request = urllib.request.Request(url)  
  
    #爬取结果  
    response = urllib.request.urlopen(request)  
  
    data = response.read()  
  
    #设置解码方式  
    data = data.decode('utf-8')  




    #打印结果
    #用BeautifulSoup解析数据  python3 必须传入参数二'html.parser' 得到一个对象,接下来获取对象的相关属性
    html=BeautifulSoup(data,'html.parser')
    dataArray = html.find_all('li', 'pj_area_data_item')


    cityAirQualityArray = []
    # 获取想要数据的字典格式
    for ulData in dataArray:
        cityName = ulData.find('a', 'pjadt_location')
        pm25Value = ulData.find('span', 'pjadt_pm25')
        aqiValue = ulData.find('span', 'pjadt_aqi')


        # 去除指定字符串
        pm25 = '' + str(pm25Value.get_text())
        pm25 = pm25.replace('μg/m³', '')
        # 去掉左右两边空格
        pm25 = pm25.strip()


# 设置字典
        cityAndPm25Dict = {}
        cityAndPm25Dict.setdefault('city', cityName.get_text())
        cityAndPm25Dict.setdefault('pm25', pm25)
        cityAndPm25Dict.setdefault('aqi', aqiValue.get_text())
        
        # 添加到数组中
            # 判断是否数据已存在
        isExist = False
        #pdb.set_trace()  # 调试
        for cityData in cityAirQualityArray:
            myCity = cityData['city']
            if myCity == cityName.get_text():
                isExist = True


        if isExist != True:
            cityAirQualityArray.append(cityAndPm25Dict)


    dataString = json.dumps(cityAirQualityArray)

    return "{\"status\":\"101\",\"msg\":\"操作成功\",\"data\":" + dataString + "}"

run(host='0.0.0.0', port=8080, debug=True)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Macle_Chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值