python自动定位天气查询助手

import requests  
import re
import json
import time
from pypinyin import lazy_pinyin
from bs4 import BeautifulSoup
def get_ip():  
    response = requests.get("http://"+str(time.localtime().tm_year)+".ip138.com/ic.asp")  
    ip = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",response.content.decode(errors='ignore')).group(0)  
    return ip
def word_to_pinyin(word):
    return ''.join(lazy_pinyin(word))
#获取www.tianqi.com的天气,参数:地名拼音
def data_of_tianqi(addr):
    response = requests.get("https://www.tianqi.com/"+addr+"/")
    soup = BeautifulSoup(response.text, 'html.parser')
    tag_dd = soup.find_all(name='dd')
    tag_span = soup.find_all(name='span')[0]
    temp = str(soup.find_all(name='b')[0])[3:-4]#温度
    city_html = BeautifulSoup(str(tag_dd[0]), 'html.parser')
    city = str(city_html.find_all(name='h2'))[5:-6]#城市
    week = str(tag_dd[1])[17:-5]
    weather_and_temp = str(tag_span)[9:-7].split('</b>')
    weather = weather_and_temp[0]#天气
    temp = str(soup.find_all(name='b')[0])[3:-4]#实时温度
    temp_from_to = weather_and_temp[1]#温度范围
    shidu = str(tag_dd[3]).replace("</b>","").replace("</dd>","").split("<b>")[1]#湿度
    fengxaing = str(tag_dd[3]).replace("</b>","").replace("</dd>","").split("<b>")[2]#风向
    ziwaixian = str(tag_dd[3]).replace("</b>","").replace("</dd>","").split("<b>")[3]#紫外线
    other_info = str(tag_dd[4])[57:-12].replace('</h5><h6>','<br/>').replace('</h6><span>','<br/>').split('<br/>')#空气质量、PM、日出、日落
    info = []
    info.append(city)
    info.append(week)
    info.append(weather)
    info.append(temp)
    info.append(temp_from_to)
    info.append(shidu)
    info.append(fengxaing)
    info.append(ziwaixian)
    info.append(other_info)
    return info
request = requests.get("http://ip.taobao.com/service/getIpInfo.php?ip="+get_ip())
data = data_of_tianqi(word_to_pinyin(json.loads(request.text)['data']['city']))
print(data)
工作原理:程序会根据IP地址定位城市,然后自动查询本城市的实时天气。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Louistinda

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

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

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

打赏作者

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

抵扣说明:

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

余额充值