【无标题】python获取城市天气

该代码段使用Python的requests库获取天气网站的HTML页面,然后通过正则表达式提取JSON数据,再利用json模块将其转换为字典,从而获取特定城市的天气信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
import re
import time
import json

城市ID

city_id = ‘101110101’

获取毫秒

t = time.time()
millisecond = int(round(t * 1000))

设置headers

headers = {‘Accept’: ‘text/html, application/xhtml+xml, image/jxr, /’,
‘Accept-Encoding’: ‘gzip, deflate’,
‘Accept-Language’: ‘zh-Hans-CN, zh-Hans; q=0.5’,
‘Connection’: ‘Keep-Alive’,
‘Host’: ‘d1.weather.com.cn’,
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/’
‘63.0.3239.132 Safari/537.36’,
‘Referer’: ‘http://www.weather.com.cn/weather1dn/’ + city_id + ‘.shtml’
}
res = requests.get(‘http://d1.weather.com.cn/sk_2d/’ + city_id + ‘.html?_=’ + str(millisecond), params=None,
headers=headers)
res.encoding = ‘utf-8’
res.raise_for_status()
content = res.text
tqRegex = re.compile(r’{[^}]*}')
json_str = tqRegex.search(content)
dict_json = json.loads(json_str.group())
print(dict_json)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值