1. 程式人生 > >python 登入網站指令碼以及錯誤requests.exceptions.ConnectionError[Errno -2] Name or service not known解決方法

python 登入網站指令碼以及錯誤requests.exceptions.ConnectionError[Errno -2] Name or service not known解決方法

最新自己做了一個網站,需要定時更新,自己懶得天天更新,所以寫了一個指令碼放在伺服器上定時更新。嘿嘿


在這裡我用的是Python 3.7  pip3 

首先,我們需要開啟你想登陸的網站,輸入賬號密碼,用fiddler抓包,看看他的post請求都有什麼內容。

看到它有post裡面帶著4個引數,好,接下來我們就用Python 模擬這4個引數。

原理是:模擬傳送post請求,得到post的結果。

import requests
def LoginByPost():    
    loginUrl='http://xxx.xxx/xxx/xxx.xxx?s=xxxxxx'
    postData={'user_name':'xxxx','user_pwd':'xxxxx','submit':'登入','__hash__':'xxxxx'}
    s=requests.session()
    rs=s.post(loginUrl,postData)
    rs.encoding='utf-8'
    print(rs.text)
LoginByPost()

這裡我用到了requests庫,登入的地址是你抓包後它自己跳轉的地址(有的網站輸入登陸的後臺他會跳轉的)。

Python3 test.py  之後,為什麼沒有效果呢?

仔細觀察才發現,你模擬的post只是一個,你需要模擬人家所有的post才可以被認為是一個完整的登入請求。

如下圖:

藍色的還有四個,你必須都得寫上,然後才能被認為是正常登陸,每個url是不同的,請注意一下。

有時候會有這樣的報錯:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='xxx.xxx.xxx', port=80): Max retries exceeded with url: /xxx/xxx.xxx?s=xxx (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at xxxxxx>: Failed to establish a new connection: [Errno -2] Name or service not known'))

這是超過了最大請求次數,也可能是你網路不好,解決的方法:

加上 

@retry(需要捕獲的異常,延遲幾秒)

from retry import retry
@retry(requests.exceptions.ConnectionError,delay=2)

用這樣的方法可以讓他在遇到這個異常不成功的時候一直髮送請求,直到得到正確結果為止。

後面自動更新的引數就不放出來了,它是通過訪問特定形式的長url來達到更新的。

這個坑饒了我很長時間,網上的辦法試了都沒成效,這個就當是暴力請求吧,hahahahahaha~