根據本地ip獲取地理位置,再根據地理位置,獲取天氣


import json,requests
from urllib.request import urlopen
from pyquery import PyQuery as pq
from lxml import etree as et



def getIp():   #獲取本地網絡ip
html_text = et.HTML(requests.get("https://ip.cn/").text)
ip = html_text.xpath('//span/text()')[5].replace(':','').replace(' ','')
print(ip)
return ip

def get_ip_area(ip): #通過ip獲取地理位置
try:
apiurl = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip
content = urlopen(apiurl).read()
data = json.loads(content)['data']
code = json.loads(content)['code']
if code == 0: # success
print(data['country_id'])
print(data['area'])
print(data['city'])
print(data['region'])
else:
print(data)
return data
except Exception as ex:
print(ex)

def weather():   #獲取本地天氣

res = json.loads(pq('https://www.toutiao.com/stream/widget/local_weather/data/?city=%s'%city).text())
local_weather=res['data']['weather']
return local_weather
data里面有四個參數,國家id,國家簡稱,本地,本地所屬的省會。local_weather獲取了本地所有的天氣,可自己選取所要用的拿出來用,將這幾個函數封裝好,以便以后須用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM