利用微信定时给朋友发送消息 (新闻,故事,天气等)

一、步骤:

1、需要获取新闻,故事,天气等相关信息;

2、获取需要跟随新闻,故事,天气等一起发送的情话信息;

3、将内容发送到微信

二、代码

利用微信定时给朋友发送消息(新闻,故事,天气等)

from pyquery import PyQuery

from wxpy import *

from threading import Timer

import requests

import random

将二维码打印出来

bot = Bot()

获取网络情话

def qinghua():

# 随机生成页数

page_random = random.randint(16, 4870)

url = "http://www.ainicr.cn/qh/"+str(page_random)+".html"

header = {"User-Agent":
              "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"}

html = requests.get(url,headers=header).text

#将获取的内容存入的列表中

nr_list = []

doc = PyQuery(html)

# 爬取网站中的文字

nr = doc(".border_30 .askbody .stbody a p ")

for item in nr.items():

    # 将爬取的文字插入到列表中

    nr_list.append(item.text())

# 随机获取列表中文字

return nr_list[random.randint(0,len(nr_list))]

def wendu():

#温度API

w_url = "http://t.weather.sojson.com/api/weather/city/101120201"

response = requests.get(w_url)

city = response.json()['cityInfo']['city']

data = response.json()['data']

#接口内容

time = "时间:"+str(data['forecast'][0]['ymd'])

city = "城市:"+str(city)

shidu = "湿度:"+str(data['shidu'])

pm25 = "PM2.5:"+str(data['pm25'])

pm10 = "PM10:"+str(data['pm10'])

quality = "空气质量:"+str(data['quality'])

forecast_high = "最高温度:"+str(data['forecast'][0]['high'].split()[1])

forecast_low = "最低温度:"+str(data['forecast'][0]['low'].split()[1])

ganmao = '感冒提醒(指数):'+str(data['ganmao'])

nr = city+"\n"\

     +time+"\n"\

     +shidu+"\n"\

     +pm25+"\n"\

     +pm10+"\n"\

     +quality+"\n"\

     +forecast_high+"\n"\

     +forecast_low+"\n"\

     +ganmao+"\n"+"\n"\

     +qinghua()


return nr

def send_new():

try:

    content = wendu()

    # 获取微信名称,注:不是备注,也不是微信号

    my_friend = bot.friends().search("小明")[0]

    # 发送消息

    my_friend.send(content)

    # 定时发送,86400秒(1天),发送一次

    t = Timer(86400, send_new)

    t.start()

except:

    # 自己的微信名称

    my_friend = bot.friends().search("小兰")[0]

    my_friend.send("今天发送消息失败!")

if name == "main":
send_new()

三、示例

image.png

1 回帖
请输入回帖内容 ...
  • xiaojian

    充分运用 python 知识呀