扣子入门教程02 模仿一个天气插件


-
直接打开city.js文件会出现乱码。 -
保存为TXT文件是因为coze不支持js文件上传。




import reasync def main(args: Args):city = args.params.get('city')filename=args.params.get('filename')# with open(filename,'r',encoding='utf-8') as f:# content=f.read()content=re.search(r'\{.*\}',filename,re.DOTALL)if content:content=content.group()data=eval(content)area={}for outer in data.values():for middle in outer.values():for v in middle.values():area[v['NAMECN']]=v['AREAID']area_code=area.get(city)if area_code:return {'success':True,'city':city,'areaid':area_code}else:return {'success':False,'city':city,'areaid':'未找到'}


import urllib.requestimport reimport jsonasync def main(args: Args):areaid = args.params.get('areaid')city = args.params.get('city')url = f'https://www.weather.com.cn/weather1d/{areaid}.shtml'try:# 使用 urllib 发送请求req = urllib.request.Request(url,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'})with urllib.request.urlopen(req, timeout=10) as response:html = response.read().decode('utf-8')result = {city: {}}# 提取 hidden_title 的 valuehidden_match = re.search(r'<input[^>]*id="hidden_title"[^>]*value="([^"]*)"', html)if hidden_match:data = hidden_match.group(1).split(' ')# 解析数据if len(data) > 1:result[city]['week'] = data[1]if len(data) > 3:result[city]['weather'] = data[3]if len(data) > 5:result[city]['temperature'] = data[5]# 提取更新时间update_match = re.search(r'<input[^>]*id="fc_24h_internal_update_time"[^>]*value="([^"]*)"', html)if update_match:result[city]['update_time'] = update_match.group(1)return {'success': True,'data': result,'error':''}except Exception as e:return {'success': False,'error': str(e),'data':{}}



夜雨聆风