本人python新手一枚。剛看完python3的基礎教程,本著“實驗出真理”的原則,自己嘗試寫了一段程式《訪問家庭路由器主頁+賬號登錄路由器》。
家里路由器是TP-LINK的。
1,路由器主頁地址 http://192.168.1.1
2,登錄視窗只有密碼輸出,沒有賬號輸入。

3,python3.7.7+自帶的IDE
使用requests訪問沒有問題。
使用urllib的urlopen就會出錯“urllib.error.HTTPError: HTTP Error 400: Bad Request”。
import pwdEncrypt #自己網路上COPY的密碼加密演算法
import requests
import json
import urllib
url = "http://192.168.1.1/"
heads ={
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Length": "54", #urllib.error.HTTPError: HTTP Error 400: Bad Request
"Content-Type": "application/json; charset=UTF-8",
"Host": "192.168.1.1",
"Origin": "http://192.168.1.1/",
"Referer": "http://192.168.1.1/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
pwd = pwdEncrypt.encrypt_pwd('123456')
datas = {
"method":"do",
"login":{"password":pwd}
}
def LoginRouterRequests():
req = requests.post(url,json=datas,headers=heads,verify=False)
print(req)
print(req.text)
def LoginRouterUrllib()
res = urllib.request.Request(url,urllib.parse.urlencode(datas).encode(),heads)
req = urllib.request.urlopen(res)
print(req)
print(req.msg)
print(req.read().decode('utf-8'))
LoginRouterRequests()
LoginRouterUrllib()
手動一步步排查,發現問題在于heads中的"Content-Length"欄位。
使用urlopen,如果注釋掉"Content-Length",程式不會報錯,但路由器無法通過賬號驗證。
請問大俠,這個問題如何解決啊???
uj5u.com熱心網友回復:
"Content-Length"是本次發送訊息的內容長度,你又沒有檢測內容長度就放一個固定值,當然要出錯誤了uj5u.com熱心網友回復:
這個“Content-Length:54”是我從chrome里面查看的資料,當時從瀏覽器里輸入的是正確的賬號密碼呢。轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41867.html
