zoukankan      html  css  js  c++  java
  • 24.API爬天气预报数据

    1.免费注册API 地址: https://console.heweather.com/
    必须要用IE浏览器打开,注册邮箱激活,打开控制台,如图:

    认证key是访问api的钥匙

    2.阅读api说明开发文档

    地址:https://www.heweather.com/documents/api/v5/url

    可以看到免费的用户只能访问一个服务器节点:

    
    
    3.了解调用接口的方法
    请求参数如下:
    之后就需要拼接参数组成请求url
    https://free-api.heweather.com/v5/weather?city=yourcity&key=yourkey
    4.获取城市ID代码
    链接地址:https://cdn.heweather.com/china-city-list.txt
    这里数据是乱码的,跟网页编码有关系。
    5.获取城市代码
    # coding:utf-8
    import requests
    url = 'https://cdn.heweather.com/china-city-list.txt'
    response = requests.get(url)
    data = response.text
    # print(data)
    cont = data.split('
    ')
    # 去除头部多余标签
    for i in range(6):
        cont.remove(cont[0])
        # print(cont)
    #循环遍历,输出id
    for j in cont:
        print(j[2:14])

    执行效果如下:

    6.拼接url完善代码
    
    # coding:utf-8
    import requests
    import random,time
    url = 'https://cdn.heweather.com/china-city-list.txt'
    response = requests.get(url)
    data = response.text
    # print(data)
    cont = data.split('
    ')
    # 去除头部多余标签
    for i in range(6):
        cont.remove(cont[0])
        # print(cont)
    #循环遍历,输出id
    for j in cont:
        # print(j[2:14])=
        link_url= 'https://free-api.heweather.com/v5/weather?city={}'.format(j[2:14])+'&key=a3a4f84e9d68491e8b2e9d61c61df7c2'
        print(link_url)
        html = requests.get(link_url)
        time.sleep(random.randint(1,2))
        print(html.text)

    代码报错:

    是由于网站把这个借口给关闭了,已经无法使用,但调用api接口的方式大概就是这样。

    模拟获取请求参数拼接请求url去获取数据,其实就和使用代理ip差不多。

  • 相关阅读:
    令我印象最深刻的三个老师
    硬盘大于2T安装CentOS7.X时要注意分区
    Linux网卡配置
    Python13:文件操作
    Python12:集合
    Python11:字典
    Python10:String字符串
    Python09:元组
    Python08:列表
    Python07:模块初识
  • 原文地址:https://www.cnblogs.com/lvjing/p/9988961.html
Copyright © 2011-2022 走看看