python脚本抓取天气信息并发给微信好友

  最近上海天气变化较大,为了提醒家人及亲朋好友注意关注天气,产生了这个想法。

话不多说,直接上代码,我这里选取特定好友发送。

#!/usr/bin/env python
# encoding: utf-8

"""
@version: ??
@author: heyifei
@email:[email protected]
@license: Apac_he Licence 
@file: sendweathertoone.py
@time: 2017/9/2 22:07
"""

import requests as req
from lxml import etree
import itchat


# 定义url
shanghai_url = "http://www.nmc.cn/publish/forecast/ASH/shang-hai.html"

changde_url = "http://www.nmc.cn/publish/forecast/AHN/chang-de.html"

chongqing_url = "http://www.nmc.cn/publish/forecast/ACQ/chong-qing.html"

# 给特定好友发送
friends = ['@xxxxxxx',
           '@xxxxxxx',
           '@xxxxxxx',
           '@xxxxxxx',
           '@xxxxxxx',
           '@xxxxxxx',
           '@xxxxxxx']

def geturlinfobyxpath(url):
    '''获取URL页面信息'''
    kv = {'user-agent': 'Mozilla/5.0'}
    r = req.get(url, headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    tree = etree.HTML(r.text)
    nodes = tree.xpath('//div[@class="day"]/div/text()')
    city = tree.xpath('//title/text()')
    updatetime = tree.xpath('//div[@class="btitle"]/span/text()')
    newnode ="".join(nodes).replace("\n", "").replace(" ", "")
    sms = "来源:xxxx为您抓取中央气象台数据。"
    sendsms = '%s%s%s%s' % (city, updatetime, newnode, sms)
    itchat.auto_login(hotReload=True)
    #给所有微信好友发送
    # friends = itchat.get_friends()
    for f in friends:
          给所有微信好友发送
          # username = f.UserName
        itchat.send_msg(sendsms, toUserName=f)
    #print(sendsms)

if __name__ == '__main__':
    geturlinfobyxpath(shanghai_url)


你可能感兴趣的:(python脚本抓取天气信息并发给微信好友)