#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/5/1 16:11
# @Author : cuijianzhe
# @File : weather.py
# @Software: PyCharm
from datetime import datetime
import urllib.request
from lxml import etree
def getWeather():
url = "http://www.weather.com.cn/weather/101010100.shtml"
response = urllib.request.urlopen(url)
html = response.read().decode()
parseHtml = etree.HTML(html)
temperatureLow = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[2]/i/text()')) # 获取今天最低温度
temperatureHigh = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[2]/span/text()')) # 获取今天最低温度
weather = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[1]/text()')) # 获取今天天气
wind = '-'.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[3]/em/span//@title')) # 获取今天风向
winL = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[3]/i/text()')) # 获取今天风级
today = datetime.now()
today = str(today.year) + '年' + str(today.month) + '月' + str(today.day) + '日'
content = 'Good moring! My Honey~\n' + \
'今天是: ' + today + '\n' + \
'北京温度: ' + temperatureLow + '-' + temperatureHigh + '℃\n' + \
'天气: ' + weather + '\n' + \
'风况: ' + wind + ' ' + winL
return content
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/5/1 16:11
# @Author : cuijianzhe
# @File : biaobai.py
# @Software: PyCharm
import requests
from bs4 import BeautifulSoup
import random
def getloverwords():
texts = []
num = int(random.randint(3, 114))
for i in range(1, num):
url = 'https://www.duanwenxue.com/huayu/biaobai/list_{}.html'.format(i)
response = requests.get(url)
texts.append(response.text)
articles = []
for text in texts:
soup = BeautifulSoup(text, 'lxml')
arttis = soup.find('div', class_='list-short-article').find_all('a', {'target': "_blank"}) # 寻找情话内容
# 通过列表推导式以及for循环获取到每个a标签里面的text内容并通过strip去除空格
articles.extend([arttis[i].text.strip() for i in range(len(arttis))])
todaywords = articles[random.randint(0, len(articles) - 1)] # 随机选取其中一条情话
return todaywords
# !/bin/env python3
########################################################
# This script is to send emails to Lijuan regularly #
# Date: 2020-5-1 #
# Author: cuijianzhe #
# Email: 598941324@qq.com #
########################################################
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import datetime
import urllib.request
from lxml import etree
from bs4 import BeautifulSoup
import requests
import random
import json
class _send():
def __init__(self):
self.Days = _send.brithday()
def getWeather(self):
from datetime import datetime
url = "http://www.weather.com.cn/weather/101010100.shtml"
response = urllib.request.urlopen(url)
html = response.read().decode()
parseHtml = etree.HTML(html)
temperatureLow = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[2]/i/text()')) #获取今天最低温度
temperatureHigh = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[2]/span/text()')) # 获取今天最低温度
weather = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[1]/text()')) #获取今天天气
wind = '-'.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[3]/em/span//@title')) #获取今天风向
winL = ''.join(parseHtml.xpath('//*[@id="7d"]/ul/li[1]/p[3]/i/text()')) #获取今天风级
today = datetime.now()
today = str(today.year) + '年' + str(today.month) + '月' + str(today.day) + '日'
content = 'Good morning! My Honey~\n' + \
'今天是: ' + today + '\n' + \
'北京温度: ' + temperatureLow + '-' + temperatureHigh + '℃\n' + \
'天气: ' + weather + '\n' + \
'风况: ' + wind +' '+ winL
return content
def getloverwords(self):
texts = []
for i in range(1, int(random.randint(3,83))):
url = 'https://www.duanwenxue.com/huayu/tianyanmiyu/list_{}.html'.format(i)
response = requests.get(url)
texts.append(response.text)
articles = []
for text in texts:
soup = BeautifulSoup(text, 'lxml')
arttis = soup.find('div', class_='list-short-article').find_all('a', {'target': "_blank"}) # 寻找情话内容
# 通过列表推导式以及for循环获取到每个a标签里面的text内容并通过strip去除空格
articles.extend([arttis[i].text.strip() for i in range(len(arttis))])
todaywords = articles[random.randint(0, len(articles) - 1)] # 随机选取其中一条情话
return todaywords
def symbol(self):
startdate = datetime.datetime(2019, 12, 9)
enddate = datetime.datetime.now()
days = int((enddate - startdate).days + 1) # 第%s天,比已经天数+1
'''
#另一种body结构体,可定义
body = """
%s\n
❤I miss you very much every day.\t%s
❤今天是我和仙女在一起的第%s天,我会至死不渝的爱你…… ❤
❤今日份小甜甜:%s \n
❤\t\t\t\t%s \n
❤ ❤ L love you ❤ ❤
""" % (self.getWeather(),self.getloverwords(),days,self.getloverwords(),self.Days)
'''
body = self.getWeather()+'\n'+\
'\n' +\
'❤I miss you very much every day.'+self.getloverwords() +'\n'+\
'❤今天是我和仙女在一起的第%s天,我会至死不渝的爱你…… ❤'%days +'\n'+\
'❤今日份小甜甜:'+ self.getloverwords()+'\n'+\
'❤ ❤ L love you ❤ ❤'+'\n' +\
'❤%s❤'%self.Days
return body
def _email(self):
try:
my_sender = '598941324@qq.com'
my_pass = 'mypassword'
my_user = ["jianzhecui@163.com",]
msg = MIMEText(self.symbol(), 'plain', 'utf-8')
msg['From'] = formataddr(["爱你的哲哥", my_sender])
msg['To'] = ','.join(my_user)
msg['Subject'] = '滴!打卡,爱你的一天'
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(my_sender, my_pass)
server.sendmail(my_sender, msg['To'].split(','), msg.as_string())
server.quit()
except Exception as err:
# logger.debug(err)
print('发送失败!', 'error: {}'.format(err))
@staticmethod
def brithday():
from datetime import datetime
future = datetime.strptime('2020-12-17 00:00:00', '%Y-%m-%d %H:%M:%S')
now = datetime.now()
delta = (future - now).days
return delta
class feishu():
def __init__(self,mobile,word):
self.mobile = mobile
self.token = feishu.get_token()
self.word = word
def getuserid(self):
headers_group = {
"Authorization": "Bearer %s" % self.token,
"Content-Type": "application/json"
}
try:
userurl = "https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=%s" %self.mobile
res_data = requests.get(url=userurl, headers=headers_group)
code = json.loads(res_data.text).get('code')
if code == 0:
userid = json.loads(res_data.text)['data']['mobile_users'][self.mobile][0]['user_id']
return userid
else:
error = json.loads(res_data.text).get('msg')
print('请求出错:{}'.format(error))
except:
print('号码参数')
def sendmess(self):
headers_group = {
"Authorization": "Bearer %s" % self.token,
"Content-Type": "application/json"
}
message_url = "https://open.feishu.cn/open-apis/message/v4/send/"
# 发送富文本消息
data = {
"user_id": self.getuserid(),
"msg_type": "post",
"content": {
"post": {
"zh_cn": {
"title": "今日份邮件发送内容如下:",
"content": [
[
{
"tag": "text",
"un_escape": True,
"text": "%s " % word
},
{
"tag": "at",
"user_id": self.getuserid()
}
]
]
}
}
}
}
request = requests.post(url=message_url, headers=headers_group, json=data)
@staticmethod # 静态方法 类或实例均可调用
def get_token(): # 改静态方法函数里不传入self 或 cls
data = {"app_id":"cli_9xxxd","app_secret":"YJJ7UxxxxYUi"}
headers = {"Content-Type": "application/json"}
url_token = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
try:
res = requests.post(url_token, json=data, headers=headers)
if res.status_code == 200:
token = (json.loads(res.text)).get('tenant_access_token')
return token
except:
print('token参数获取失败!', 'error: {}'.format(err))
if __name__ == '__main__':
content = _send()
content._email() #发送邮件
word = content.symbol() #邮件文本结构体
mobiles = ["186xxxx6142"]
for mobile in mobiles:
fs = feishu(mobile,word)
fs.sendmess()
参考:https://blog.csdn.net/blowfire123/article/details/99173295