
正文
python定时发信息给女友
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
-
第一步,也是最难的一部
- 首先得要有个女朋友
-
利用python的第三方库wxpy来登录微信,实现消息发送功能
from wxpy import * def login():
bot = Bot(cache_path=True)
my_lover = bot.friends().search('夏叶')[0]
return my_loversearch方法接收一个昵称的字符串,它会返回一个查找到的所有条件的列表对象,我们这里只有这一个人,直接选第一个对象
-
去天气网爬取网页数据,将关于天气的信息筛选下来,整合成消息字符串
import requests
from lxml import etree def get_page(url):
r = requests.get(url)
r.encoding = r.apparent_encoding
return r.text if r.status_code == 200 else None def parse_page(html):
html = etree.HTML(html)
forecasts = html.xpath('/html/body/div[8]/div[1]/div[1]/div[2]/ul/li/a[1]/@title')
forecasts = '\n'.join(forecasts)
keys = html.xpath('/html/body/div[8]/div[2]/div[6]/ul/li/b/text()')
values = html.xpath('/html/body/div[8]/div[2]/div[6]/ul/li/a/p/text()')
day_info = {i: values[keys.index(i)] for i in keys}
message = '青哥哥今日提醒:\n\n' + '南京今日生活指数:\n' + '\n'.join(
['{}: {}'.format(i, day_info[i]) for i in day_info]) + '\n' * 3 + '南京主要地区天气预报:\n' + forecasts
return message爬虫库使用的是requests,解析库用的是xpath,最后将字符串拼接,返回消息对象
-
获取当前时间和设置闹钟
from datetime import datetime def get_time():
time = datetime.now().strftime('%H:%M:%S')
return time clock = '06:00:0{}' # 设置启动时间
interval = 3 # 设置时间间隔
time_zone = [clock.format(i) for i in range(interval)]防止电脑性能过差或cpu使用率过高导致的时间漏缺,设置一下时间间隔,我这里设置的是三秒,最后将设置时间区间
-
主函数发送消息
def main(my_lover):
url = 'http://www.tianqi.com/nanjing/'
html = get_page(url)
message = parse_page(html)
my_lover.send(message)不同城市的url可以去天气网自定义,一般网页的结构是不会变得
-
判断时间,最后的完整代码
from time import sleep
from datetime import datetime
from wxpy import *
import requests
from lxml import etree def login():
bot = Bot(cache_path=True)
my_lover = bot.friends().search('夏叶')[0]
return my_lover def get_page(url):
r = requests.get(url)
r.encoding = r.apparent_encoding
return r.text if r.status_code == 200 else None def parse_page(html):
html = etree.HTML(html)
forecasts = html.xpath('/html/body/div[8]/div[1]/div[1]/div[2]/ul/li/a[1]/@title')
forecasts = '\n'.join(forecasts)
keys = html.xpath('/html/body/div[8]/div[2]/div[6]/ul/li/b/text()')
values = html.xpath('/html/body/div[8]/div[2]/div[6]/ul/li/a/p/text()')
day_info = {i: values[keys.index(i)] for i in keys}
message = '青哥哥今日提醒:\n\n' + '南京今日生活指数:\n' + '\n'.join(
['{}: {}'.format(i, day_info[i]) for i in day_info]) + '\n' * 3 + '南京主要地区天气预报:\n' + forecasts
return message def get_time():
time = datetime.now().strftime('%H:%M:%S')
return time clock = '06:00:0{}' # 设置启动时间
interval = 3 # 设置时间间隔
time_zone = [clock.format(i) for i in range(interval)] def main(my_lover):
url = 'http://www.tianqi.com/nanjing/'
html = get_page(url)
message = parse_page(html)
my_lover.send(message) if __name__ == '__main__':
my_lover = login()
print('waiting......')
while True:
time = get_time()
if time in time_zone:
main(my_lover)
print(time)
sleep(interval)
sleep(1) # 程序休眠一秒,减少cpu的压力







