您的位置:首頁技術文章
文章詳情頁

python對接ihuyi實現短信驗證碼發送

瀏覽:3日期:2022-07-26 09:09:21

在日常生活中我們經常會遇到接收短信驗證碼的場景,Python也提供了簡便的方法實現這個功能,下面就用代碼來實現這個功能。

一般我們需要租借短信供應商的服務器發送短信。如果是用于自學會有一定免費條數的限額。

我們就借用互憶的平臺來是實現代碼。

首先需要訪問http://www.ihuyi.com/sms.html注冊私人賬號,注冊完之后進入個人信息界面會看到自己的賬號和密鑰。

所需導入的包:

import requests,random,bs4

requests模塊用于發送請求,random模塊用于產生驗證碼,bs4模塊用于解析服務器響應信息。如果沒有安裝這些包,打開cmd,輸入pip install 包名 進行安裝。

一般手機驗證碼都是隨機四位數,所以我們用一個函數來實現,主要用random函數產生4位隨機數并返回。

def create_verify_code(): '''隨機產生一個4位數驗證碼''' verify_code = ’’ for i in range(4): verify_code += str(random.randint(0,9)) return verify_code

接著就要利用供應商的API接口來發送短信,API文檔在互憶官網上就能下載到或者到自己賬戶中就能找到。

headers用于構造請求頭,我們只需傳入手機號和要發送的文本,然后利用requests發送post請求給服務器,就會收到返回信息。

def sendmessagecode(phonenum,content): '''發送短信驗證碼''' headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} data = {’account’:account,’password’:password,’mobile’:phonenum,’content’:content} return requests.post(host,data=data,headers=headers)

在收到服務器返回信息后,我們就可以解析信息,來判斷服務器是否發送成功。

response = sendmessagecode(phoneNum,content) # 用response來接收響應信息

判斷是否與服務器聯通,若鏈接成功再進行下一步,否則打印失敗信息。

if 200 == response.status_code: TODO... else: print(’與服務器連接失?。骸?response.status_code)

若響應成功,就利用BeautifulSoup來解析響應信息。

soup = bs4.BeautifulSoup(response.text,features=’lxml’) # 構造soup對象code = soup.find(’code’).string msg = soup.find(’msg’).stringif 2 == code: # 若服務器響應碼為2,說明短信發送成功 print(’code: %s msg: %s ’ %(code,msg))else: print(’code: %s msg: %s ’ %(code,msg))

全文代碼:

#! python3# 測試發送短信,所用服務器為互億測試賬號import requests,random,bs4 host = ’http://106.ihuyi.com/webservice/sms.php?method=Submit’account = ’C27187646’password = ’64713042f161ae0555e9617afef40610’ def sendmessagecode(phonenum,content): '''發送短信驗證碼''' headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} data = {’account’:account,’password’:password,’mobile’:phonenum,’content’:content} return requests.post(host,data=data,headers=headers) def create_verify_code(): '''隨機產生一個4位數驗證碼''' verify_code = ’’ for i in range(4): verify_code += str(random.randint(0,9)) return verify_code if __name__ == ’__main__’: phoneNum = ’159XXXXXXXX’ code = create_verify_code() content = ’您的驗證碼是:%s。請不要把驗證碼泄露給其他人。’ %code response = sendmessagecode(phoneNum,content) print(’短信內容:’,content) if 200 == response.status_code: soup = bs4.BeautifulSoup(response.text,features=’lxml’) code = soup.find(’code’).string msg = soup.find(’msg’).string if 2 == code: print(’code: %s msg: %s ’ %(code,msg)) else: print(’code: %s msg: %s ’ %(code,msg)) else: print(’與服務器連接失?。骸?response.status_code)

以上就是python對接ihuyi實現短信驗證碼發送的詳細內容,更多關于python短信驗證碼發送實例的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区