微信自动发送信息python脚本

今天早上突然想做个小东西玩。

参考博客

代码如下:

from __future__ import unicode_literals
from threading import Timer
from wxpy import *
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import schedule
import time
import urllib
import json
import re

bot = Bot(cache_path=True)


# 自定义爬虫函数
def job():
#北京 resp = urlopen('http://www.weather.com.cn/weather/101010100.shtml')
resp = urlopen('http://www.weather.com.cn/weather/101190101.shtml')
soup = BeautifulSoup(resp, 'html.parser')
tagToday = soup.find('p', class_="tem") # 第一个包含class="tem"的p标签即为存放今天天气数据的标签
try:
temperatureHigh = tagToday.span.string # 有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。
except AttributeError as e:
temperatureHigh = tagToday.find_next('p', class_="tem").span.string # 获取第二天的最高温度代替

temperatureLow = tagToday.i.string # 获取最低温度
weather = soup.find('p', class_="wea").string # 获取天气
contents = '南京' + '\n' + '最高温度:' + temperatureHigh + '\n' + '最低温度:' + temperatureLow + '\n' + '天气:' + weather
return contents


def get_news():
url = "http://open.iciba.com/dsapi/" # 从网站获取信息
r = requests.get(url)
content = r.json()['content']
note = r.json()['note']
weather_info = job()
return content, note, weather_info


def send_news():
try:
content, note, weather = get_news()
my_friend = bot.friends().search(u'')[0] # 好友姓名
# my_friend.send(content)
# my_friend.send(note)
my_friend.send(weather)
my_friend.send("this is a python test! Morning!")
# my_friend.send("this is the second python test ! Morning")
"""
schedule.every().day.at("12:30").do(job)
# 规定每天12:30执行job()函数
while True:
schedule.run_pending()#确保schedule一直运行
time.sleep(1)
"""
t = Timer(60, send_news) # 60s 发送一次
t.start()

except:
my_friend = bot.friends().search('帆')[0]
my_friend.send(u'send error')


if __name__ == "__main__":
send_news()
bot.join() # 保证网页版微信在登录状态