天天看點

根據本地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擷取了本地所有的天氣,可自己選取所要用的拿出來用,将這幾個函數封裝好,以便以後須用。