python爬虫類自動天気予報を実現

3162 ワード

2年前に書いた自動天気予報のシナリオは、今日テストしてもまだ実行できることがわかりました.itchatパッケージを利用して、実際に呼び出されたのはウェブ版の微信のインタフェースで、1つの欠点は時間が長くなるとアクティブではなくオフラインになり、win 7の計画タスクに1分おきに自分に空のメッセージを送信するように設定できることです.
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 30 14:55:57 2017

@author: moses1213
"""

from pyquery import PyQuery as pq
import itchat
import datetime


def nickname_to_id(nickname,tag):
    #tag = 0  , tag = 1  
    if tag == 0:
        pyitem = itchat.search_friends(name = nickname)
    elif tag == 1:
        pyitem = itchat.search_chatrooms(name = nickname)
    else:
        print(" !
") return None return pyitem[0].UserName //create a dict for friends' city receiver = {} //create a dict for cities' chinese name city_d = {'chengdu':' ', 'beijing':' ', 'shanghai':' ', 'guangzhou':' '} itchat.auto_login(hotReload=True) #itchat.auto_login(hotReload=true) itchat.dump_login_status() def get_weather(city): web_head = 'http://weather.sina.com.cn/' URL = web_head + city weather_html = pq(URL,encoding="utf-8") temp_range = weather_html('.wt_fc_c0_i_temp')('p').eq(0).text() temp_ls = temp_range.split('/') temp_max = temp_ls[0].lstrip().rstrip() temp_min = temp_ls[1].lstrip().rstrip() curr_temp = weather_html('.slider_degree').text() weather_bar = weather_html('.slider_detail')('p').text() weather_ls = weather_bar.split('|') pollution_index = weather_html('.slider_warn_i_tt')('p').text() air_quality = weather_html('.slider_warn_val3')('p').text() curr_date = weather_html('.slider_ct_date')('p').text() update_date = weather_html('.slider_ct_time').text() conition = weather_ls[0].lstrip().rstrip() wind = weather_ls[1].lstrip().rstrip() humidity = weather_ls[2].lstrip().rstrip() weather = city_d[city] + ' ' + curr_date + '
' + ' ' + conition + ', ' + wind + '
' + temp_min + '~' + temp_max + ', '+ curr_temp + '
' + humidity + '
: ' + pollution_index + '
: ' + air_quality + '
( ' + update_date + ')' return weather def time_diff(send_time): send_time_list = send_time.split(':') hh = int(send_time_list[0]) mm = int(send_time_list[1]) curr_time = datetime.datetime.now() if hh < curr_time.hour: return (curr_time.hour-hh)*60+curr_time.minute-mm elif hh > curr_time.hour: return (hh-curr_time.hour)*60+mm-curr_time.minute else: return abs(mm-curr_time.minute) def send_weather(nickname,tag, send_time): if time_diff(send_time) < 1: user_id = nickname_to_id(nickname,tag) for city in receiver[nickname]: itchat.send(msg=get_weather(city), toUserName=user_id) def send_text(nickname,tag): user_id = nickname_to_id(nickname,tag) itchat.send(msg='test',toUserName=user_id)