這篇文章主要講解了python對接ihuyi如何實現短信驗證碼發送,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
一般我們需要租借短信供應商的服務器發送短信。如果是用于自學會有一定免費條數的限額。
我們就借用互憶的平臺來是實現代碼。
首先需要訪問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('與服務器連接失?。?#39;,response.status_code)
若響應成功,就利用BeautifulSoup來解析響應信息。
soup = bs4.BeautifulSoup(response.text,features='lxml') # 構造soup對象 code = soup.find('code').string msg = soup.find('msg').string if 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('與服務器連接失?。?#39;,response.status_code)
看完上述內容,是不是對python對接ihuyi如何實現短信驗證碼發送有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。