pyhthon 利用爬虫结合阿里大于短信接口实现短信发送天气预报

    xiaoxiao2021-03-25  100

    感谢林海大哥提供的阿里短信API,使我重新了解pythond的面向对象这个知识点。关于API的使用不多说直接上链接:阿里大于API说明

    API文档:

    # -*- coding: utf-8 -*- ''' SDK for alidayu requires: python3.x, requests @author: raptor.zh@gmail.com requests 打包出错故替换成urllib库 ''' #import requests import urllib.request import urllib.parse import hashlib from time import time import json import logging logger = logging.getLogger(__name__) class RestApi(object): def __init__(self, key, secret, url="https://gw.api.tbsandbox.com/router/rest", partner_id=""): self.key = key self.secret = secret self.url = url self.partner_id = partner_id def sign(self, params): #=========================================================================== # '''签名方法 # @param parameters: 支持字典和string两种 # ''' #=========================================================================== if isinstance(params, dict): params = "".join(["".join([k, v]) for k,v in sorted(params.items())]) params = "".join([self.secret, params, self.secret]) sign = hashlib.md5(params.encode("utf-8")).hexdigest().upper() return sign def get_api_params(self): params = {} try: [params.__setitem__(k, getattr(self, k)) for k in self.get_param_names()] except AttributeError: raise Exception("Some parameters is needed for this api call") [params.__setitem__(k, getattr(self, k)) for k in self.get_option_names() if hasattr(self, k)] print(params) return params def getResponse(self, authorize=None): sys_params = { "method": self.get_api_name(), "app_key": self.key, "timestamp": str(int(time() * 1000)), "format": "json", "v": "2.0", "partner_id": self.partner_id, "sign_method": "md5", } if authorize is not None: sys_params['session'] = authorize params = self.get_api_params() sign_params = sys_params.copy() sign_params.update(params) sys_params['sign'] = self.sign(sign_params) headers = { 'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8', "Cache-Control": "no-cache", "Connection": "Keep-Alive", } #headers = {"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"} sys_params.update(params) logger.debug(json.dumps(sys_params)) data = urllib.parse.urlencode(sys_params).encode('utf-8') r = urllib.request.Request(self.url, data, headers) result = urllib.request.urlopen(r).read().decode('utf-8') return result #r = requests.post(self.url, params=sys_params, headers=headers) #r.raise_for_status() #return r.json() class AlibabaAliqinFcSmsNumSendRequest(RestApi): def get_api_name(self): return "alibaba.aliqin.fc.sms.num.send" def get_param_names(self): return ['sms_type', 'sms_free_sign_name', 'rec_num', 'sms_template_code'] def get_option_names(self): return ['extend', 'sms_param'] 爬取某地天气代码:

    #-*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import re def GetWeather(): url = "http://taian1.tianqi.com/****/" seq = requests.get(url) #尝试用requests库来解析网页 html_count = seq.text #得到网页源码 soup = BeautifulSoup(html_count,"html.parser") #创建一个Beautifulsoup对象,并解析 today_gaishu = soup.find_all('div',"todaygaishu") #查找<div class=todaygasihu>标签 today_gaishu=str(today_gaishu) #将beautifulsoup类型转化为字符串 weather_today = re.findall(r'"todaygaishu">(.+)<br>',today_gaishu) #通过正则得到今天的天气 weather_tomorrow = re.findall(r'<br>(.+)<i style',today_gaishu) #通过正则得到明天的天气 weather = weather_today + weather_tomorrow a = str(weather[0]) a = a[7:] a = a.split(",") today_weather = a[0] +","+ a[2] b = str(weather[1]) b = b[7:] b = b.split(",") tomorrow_weather = b[0] + ","+b[2] tianqi = {"weather_today":today_weather,"weather_tomor":tomorrow_weather} print(tianqi) return tianqi 调用API传入短信变量代码:

    import json from alidayu import AlibabaAliqinFcSmsNumSendRequest from TianQi_Spider import GetWeather def sms_send(phone): weather = GetWeather() appkey = '236******' secret = 'e81e81691c0cdbaacbfae2f***' url = 'https://eco.taobao.com/router/rest' # params = {'name':'ks2','num':'50'} req = AlibabaAliqinFcSmsNumSendRequest(appkey, secret, url) req.extend = "123456" req.sms_type = "normal" req.sms_free_sign_name = "**天气" #req.sms_param="{\"weather\":\"\"{name}.format(name=today_weather)\"\"}" #req.sms_param=json.dumps(params) req.sms_param=str(weather) req.rec_num = phone req.sms_template_code = "SMS_482***" try: resp = req.getResponse() print(resp) except Exception as e: print(e) sms_send('178***') print("天气已爬取,短信发送成功")

    转载请注明原文地址: https://ju.6miu.com/read-25660.html

    最新回复(0)