Python 爬虫篇-利用BeautifulSoup库爬取墨迹天气网的天气信息实例演示,调用墨迹天气api接口获取空气质量

时间:2022-07-25
本文章向大家介绍Python 爬虫篇-利用BeautifulSoup库爬取墨迹天气网的天气信息实例演示,调用墨迹天气api接口获取空气质量,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

安装方法pip install BeautifulSoup4 BeautifulSoup详细使用文档

墨迹天气抓取演示

墨迹天气没有提供专门的天气接口api,但我们可以用BeautifulSoup来简单的爬取到信息。 墨迹天气真的很准呢,里面还有空气质量可以直接获取到,很方便呢。

定位方法: https://tianqi.moji.com/weather/china/beijing 不确定省后面怎么拼,直接用省的拼写进入页面,然后找到对应的市县区进入后就有路径了。

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = urlopen('https://tianqi.moji.com/weather/china/beijing/haidian-district')
soup = BeautifulSoup(url, 'html.parser')   # parser 解析

alert = soup.find('div', class_="wea_alert clearfix").em
print("空气质量:" + alert.string)

weather = soup.find('div', class_="wea_weather clearfix")
print("当前温度:" + weather.em.string + "℃")
print("天气:" + weather.b.string)

运行效果图:

页面展示:

原理展示

alert = soup.find('div', class_="wea_alert clearfix")
print(alert)

先找到 class 为 wea_alert clearfix 的div标签。 alert.em 用来定位里面的em标签。 alert.em.string 用来获取em标签里的内容。