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标签里的内容。
在这里插入图片描述
喜欢的点个赞❤吧!

发布了379 篇原创文章 · 获赞 1683 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/qq_38161040/article/details/88991696