参考原博文
https://blog.csdn.net/qq_41320433/article/details/104403102
https://blog.csdn.net/qq_41320433/article/details/104403742
这里主要记录一下Twilio库的使用
在按照步骤完成账号注册以后
使用Twilio分配的手机号发短信会出现保报错
翻译过来是号码没有得到认证
原因是因为我们的试验号码只能对认证过的号码打电话发短信
如果想要给某个号码发短信,需要在以下网址
https://www.twilio.com/console/phone-numbers/verified
将收件人号码认证(这里也需要接收验证码)
认证之后该号码即可用啦
源代码附上
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 15:27:39 2020
@author: MACHENIKE
"""
# 小技巧:pycharm中,alt+enter快捷键可快速安装缺失库
import json
import requests
# 爬取爱词霸每日鸡汤
def get_iciba_everyday_chicken_soup():
url = 'http://open.iciba.com/dsapi/' # 爱词霸网站地址
r = requests.get(url)
all = json.loads(r.text) # 获取到json格式的内容,内容很多
# print(all) # json内容,通过这行代码来确定每日一句的键名
Englis = all['content'] # 提取json中的英文鸡汤
Chinese = all['note'] # 提取json中的中文鸡汤
everyday_soup = Englis+'\n'+Chinese # 合并需要的字符串内容
return everyday_soup # 返回结果
print(get_iciba_everyday_chicken_soup())
import urllib.request # 需要安装 urllib 库
from bs4 import BeautifulSoup #需要安装 bs4 库
def get_weather(city_pinyin):
# 声明头,模拟真人操作,防止被反爬虫发现
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64;\
rv:23.0) Gecko/20100101 Firefox/23.0'}
# 通过传入的城市名拼音参数来拼接出该城市的天气预报的网页地址
website = "http://www.tianqi.com/" + city_pinyin + ".html"
req = urllib.request.Request(url=website, headers=header)
page = urllib.request.urlopen(req)
html = page.read()
soup = BeautifulSoup(html.decode("utf-8"), "html.parser")
# html.parser表示解析使用的解析器
nodes = soup.find_all('dd')
tody_weather = ""
for node in nodes: # 遍历获取各项数据
temp = node.get_text()
if (temp.find('[切换城市]')):
temp = temp[:temp.find('[切换城市]')]
tody_weather += temp
# 去除字符串中的空行:
tianqi = "".join([s for s in tody_weather.splitlines(True)
if s.strip()])
return tianqi # 返回结果
# 调用封装号好的函数获取天气预报,参数‘chongqing’是重庆的拼音:
print(get_weather('wuhan'))
# 想查询哪个城市的天气情况,直接将参数替换为它的拼音即可
import time
from twilio.rest import Client # 需要装twilio库
# 获取当前时间并格式化显示方式:
send_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def send_message():
account_sid = '' # api参数 复制粘贴过来
auth_token = '' # api参数 复制粘贴过来
client = Client(account_sid, auth_token) # 账户认证
message = client.messages.create(
to="+", # 接受短信的手机号 注意写中国区号 +86
from_="“+” # api参数ActiveNumber(领取的虚拟号码
body="\n每日鸡汤:"+ get_iciba_everyday_chicken_soup() + get_weather('wuhan') + "\n——由mra 小机器人发送") #自定义短信内容
print('接收短信号码:'+message.to)
# 打印发送时间和发送状态:
print('发送时间:%s \n状态:发送成功!' % send_time)
print('短信内容:\n'+ message.body) # 打印短信内容
print('短信SID:' + message.sid) # 打印SID
send_message() # 调用执行函数