ESP32 MicroPython开发之旅 爬虫篇② 爬虫实例:获取网络天气

31 篇文章 131 订阅 ¥29.90 ¥99.00

重要内容说三遍

  • 爬虫有风险,我们必须在合情合理合法情况去玩爬虫,请不要以任何商业目的去爬取别人的网站,也不要频繁爬取别人的网站(1秒1w次有点离谱)
  • 爬虫有风险,我们必须在合情合理合法情况去玩爬虫,请不要以任何商业目的去爬取别人的网站,也不要频繁爬取别人的网站(1秒1w次有点离谱)
  • 爬虫有风险,我们必须在合情合理合法情况去玩爬虫,请不要以任何商业目的去爬取别人的网站,也不要频繁爬取别人的网站(1秒1w次有点离谱)
    在这里插入图片描述

爬虫实例:获取网络天气

获取天气

获取天气的API非常多,但是用的比较多的是心知天气提供的API,往心知天气平台(https://docs.seniverse.com/api/weather/now.html)请求当地城市天气情况,获取温度值以及城市名称

  • 获取指定城市的天气实况。付费用户可获取全部数据,免费用户只返回天气现象文字、代码和气温 3 项数据。注:中国城市暂不支持云量和露点温度。
请求API地址说明

https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=xxxx&language=zh-Hans&unit=c

这里注意一下key,需要替换为自己申请的。location表示具体城市的拼音。

在这里插入图片描述

这里需要自己去申请API密钥。
在这里插入图片描述

浏览器访问天气

博主这里请求广州的天气:

https://api.seniverse.com/v3/weather/now.json?key=xxxxxx&location=guangzhou&language=zh-Hans&unit=c

  • key:填写自己申请的
  • location:guangzhou

请求结果:

{"results":[{"location":{"id":"WS0E9D8WN298","name":"广州","country":"CN","path":"广州,广州,广东,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"阴","code":"9","temperature":"16"},"last_update":"2021-12-19T20:40:44+08:00"}]}
F12查看浏览器请求过程

以后我们学习爬虫或者反爬虫技术,很多情况下都会查看网络请求的整个过程,这时候可以在浏览器上按下F12.
在这里插入图片描述
在这里插入图片描述
然后我们看看响应内容的数据结构(json):
在这里插入图片描述
也就是整个json获取路径为:

  • json_str['results'][0]['location']['name']——城市名字
  • json_str['results'][0]['now']['text']——阴晴等等
  • json_str['results'][0]['now']['temperature']——温度
  • json_str['results'][0]['last_update']——更新时间
访问 https://api.seniverse.com/robots.txt

在进行爬虫之前,我们都尽量进行爬虫合法性查阅

https://api.seniverse.com/robots.txt

{"status":"The API key is invalid.","status_code":"AP010003"}

没有设定 robots.txt 也就是该网站所有页面数据都可以爬取。

ESP32访问天气 —— ujson方式
理论知识
ESP32代码细节
  • 创建 spider_weather.py文件
    在这里插入图片描述

写入以下代码:

# 导入网络模块
import network
# 导入httpclient
import lib_urequests
# 导入json库
import ujson

# 定义一个连接函数
def do_connect():
    # 创建STA模式
    sta_if = network.WLAN(network.STA_IF)
    # 返回网络工作状态
    print('network status:', sta_if.status())
    # 检查连接是否建立
    if not sta_if.isconnected():
        print('connecting to network...')
        # 激活station模式
        sta_if.active(True)
        # 连接到您的WiFi网络
        sta_if.connect('TP-LINK_5344', 'xxxxxx')
        # 返回网络工作状态
        print('network status:', sta_if.status())
        # 检查连接是否建立
        while not sta_if.isconnected():
            pass
    # 返回网络工作状态
    print('network status:', sta_if.status())
    
#自动连接
do_connect()
# 请求广州天气情况 填入自己的key
resp = lib_urequests.get('https://api.seniverse.com/v3/weather/now.json?key=xxxxxx&location=guangzhou&language=zh-Hans&unit=c')
# 打印请求结果
print(type(resp.text),resp.text)
# json字符串转为python列表类型
json_str1 = ujson.loads(resp.text)
print(json_str1['results'][0]['location']['name'])
print(json_str1['results'][0]['now']['text'])
print(json_str1['results'][0]['now']['temperature'])
print(json_str1['results'][0]['last_update'])
测试效果
  • 点击运行
>>> %Run -c $EDITOR_CONTENT
network status: 1010
network status: 1010
<class 'str'> {"results":[{"location":{"id":"WS0E9D8WN298","name":"广州","country":"CN","path":"广州,广州,广东,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"阴","code":"9","temperature":"15"},"last_update":"2021-12-19T21:40:39+08:00"}]}
广州
阴
15
2021-12-19T21:40:39+08:00
>>> 

这里用到了ujson去解析返回的json字符串,然后从中扣出我们要的字段信息。

ESP32访问天气——ure方式

这里我们试着用正则表达式的方式去扣出来想要的字段。

理论知识
ESP32代码细节
  • ("temperature":"\d*") —— 匹配温度

  • ("name":"[\u4e00-\u9fa5]*")——匹配城市名字

  • ("text":"[\u4e00-\u9fa5]*")—— 匹配阴晴

  • 创建 spider_weather_ure.py文件
    在这里插入图片描述
    写入以下代码:

# 导入网络模块
import network
# 导入httpclient
import lib_urequests
# 导入ure库
import ure

# 定义一个连接函数
def do_connect():
    # 创建STA模式
    sta_if = network.WLAN(network.STA_IF)
    # 返回网络工作状态
    print('network status:', sta_if.status())
    # 检查连接是否建立
    if not sta_if.isconnected():
        print('connecting to network...')
        # 激活station模式
        sta_if.active(True)
        # 连接到您的WiFi网络
        sta_if.connect('TP-LINK_5344', '6206908you11011010')
        # 返回网络工作状态
        print('network status:', sta_if.status())
        # 检查连接是否建立
        while not sta_if.isconnected():
            pass
    # 返回网络工作状态
    print('network status:', sta_if.status())
    
#自动连接
do_connect()
# 请求广州天气情况
resp = lib_urequests.get('https://api.seniverse.com/v3/weather/now.json?key=SBBRd0X8fidhmnBv2&location=guangzhou&language=zh-Hans&unit=c')
# 打印请求结果
print(type(resp.text),resp.text)
# 匹配
search = ure.search('("temperature":"\d*")',resp.text)
print('search1:',search.group(1))
search = ure.search('("name":"[\u4e00-\u9fa5]*")',resp.text)
print('search1:',search.group(1))
search = ure.search('("text":"[\u4e00-\u9fa5]*")',resp.text)
print('search1:',search.group(1))


测试效果
  • 点击运行
>>> %Run -c $EDITOR_CONTENT
network status: 1010
network status: 1010
<class 'str'> {"results":[{"location":{"id":"WS0E9D8WN298","name":"广州","country":"CN","path":"广州,广州,广东,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"阴","code":"9","temperature":"15"},"last_update":"2021-12-19T22:18:44+08:00"}]}
search1: "temperature":"15"
search1: "name":"广州"
search1: "text":"阴"
>>> 
  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

单片机菜鸟爱学习

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

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

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

打赏作者

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

抵扣说明:

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

余额充值