python 定时发送消息给微信好友

1、爬取爱情的文艺句子

import requests
from lxml import etree
import re

def save_file(love_sentences):
    with open('love_yaya.csv', 'a', encoding='utf-8') as f:
        for context in love_sentences:
            f.write('{}\n'.format(context))

def read_url():
    base_url = 'https://m.kuaidu.com.cn/article/207521_{}.html'
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
    }
    love_sentences = []
    for num in range(1, 11):
        url = base_url.format(num)
        resp = requests.get(url, headers=header)
        text = resp.content.decode('utf-8')
        html = etree.HTML(text)
        contexts = html.xpath('//div[@class="mycontext"]/p/text()')
        for ctx in contexts:
            ctx = re.sub(r'\n', '', str(ctx))
            ctx = re.sub(r' ', '', ctx)
            ctx = re.sub(r'[0-9]+?、', '', ctx)
            love_sentences.append(ctx)
    save_file(love_sentences)

if __name__ == '__main__':
    read_url()

2、发送给微信好友

pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple wxpy

from threading import Timer
from wxpy import *

bot = Bot()

def read_file():
    datas = []
    with open('love_yaya.csv', 'r', encoding='utf-8') as lines:
        for line in lines:
            datas.append(line)
    return datas

def send_massage(datas, i):
    try:
        end_massage = "永远爱你的狮子"
        # 获取好友备注
        my_friend = bot.friends().search(u'小明')[0]
        # 发送消息
        my_friend.send(datas[i])
        my_friend.send(end_massage)
        # 每86400秒(1天),发送1次
        i = i + 1
        item = (datas, i)
        t = Timer(86400, send_massage, item)
        t.start()
    except:
        my_friend = bot.friends().search(u'小明')[0]
        my_friend.send(datas[i])
        my_friend.send(u"今天消息发送失败了,狮子依然永远的爱你")

if __name__ == '__main__':
    datas = read_file()
    send_massage(datas, 0)

还可以用ichat包发送微信信息

3、学习知识点

python for循环

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前水果 :', fruit
从0到9遍历
for i in range(0,10):
	....

python 读取文件

f=open('/Users/michael/notfound.txt', 'r')
f.read()
f.close()

每次都这么写实在太繁琐,所以,Python引入了with语句来自动帮我们调用close()方法:

with open('/home/xbwang/Desktop/output_measures.txt','r') as f:
........

一次读取全部内容到内存

with open('file.txt', 'r') as f:
    print(f.read()) 

readlines(),with方式,逐行读取

with open("file.txt") as lines:
        for line in lines:
            print(line)

readlines(),open方式,逐行读取

# 打开文件
f = open("file.txt", "r")
print ("文件名为: ", f.name)
for line in fo.readlines():                          #依次读取每行  
    line = line.strip()                             #去掉每行头尾空白  
    print ("读取的数据为: %s" % (line))
# 关闭文件
fo.close()

python format 格式化函数

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

python 定时任务

import threading
import time

def hello(name):
    print ("hello %s\n" ) % name
    global timer
    timer = threading.Timer(2.0, hello, ["Hawk"])
    timer.start()

if __name__ == "__main__":
    timer = threading.Timer(2.0, hello, ["Hawk"])   ##每隔两秒调用函数hello
    timer.start()

注:

from threading import Timer

def send_massage(datas, i):
	item = (datas, i)
    t = Timer(86400, send_massage, item)
    t.start()

Timer函数传递的参数是一个pair类型
学习链接:https://blog.csdn.net/qq_42238397/article/details/81149617
https://www.cnblogs.com/ymjyqsx/p/6554817.html
https://www.cnblogs.com/longsongpong/p/10997692.html
https://blog.csdn.net/weixin_44022544/article/details/105691620

相关推荐
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:白松林 返回首页