爬虫经典案例之获取天气网的天气数据

爬取天气网的数据很简单,使用到的模块也很少。

from bs4 import BeautifulSoup
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0'}

# 101030100是天津的城市代码
url = 'http://www.weather.com.cn/weather/101030100.shtml'
response = requests.get(url=url, headers=headers)
# 一定要转为utf-8,不然获取的内容是乱码
response.encoding = 'utf-8'

soup = BeautifulSoup(response.text, 'html.parser')
# 当天的日期
today = soup.find('h1').string.replace('(今天)', '')
# 天气情况
weather = soup.find('p', class_='wea').string
# 温度
temperature = soup.find('p', class_='tem').find('i').string
# 风向
win = soup.find('p', class_='win').find('span').get('title')
# 风力
win_level = soup.find('p', class_='win').find('i').string
print("今天是%s号,天气是%s,气温%s,风向是%s,风力为%s。" % (today, weather, temperature, win, win_level))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dustin.Hoffman

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

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

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

打赏作者

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

抵扣说明:

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

余额充值