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('\n')
# 去除头部多余标签
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('\n')
# 去除头部多余标签
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差不多。

猜你喜欢

转载自www.cnblogs.com/lvjing/p/9988961.html