標籤:使用者 處理 password div 9.png head 資訊 class ima
1、處理登入表單
處理登入表單可以分為2步:
第一、查看網站登入的表單,構建POST請求的參數字典;
第二、提交POST請求。
開啟知乎登入介面,https://www.zhihu.com/#signin,
按f12,開啟開發人員介面:
在這裡面找到headers資訊,
現在在使用者名稱和密碼處尋找資訊,
發現使用者名稱的屬性為account,account中的內容為我們的使用者名稱;
同理,password中的內容為我們的密碼。
在登入表單中,有些key值在瀏覽器中設定了hidden值,不會顯示出來,這個時候我們需要去審查元素中去尋找,
發現了,cookie中有一個_xsrf的屬性,類似於token的作用。而這個東西的存在,就讓我們在類比登入的時候,必須將這個屬性作為參數一起加在請求中發送出去。
而擷取_xsrf則可以用之前的BeautifulSoup擷取
import requestsfrom bs4 import BeautifulSoup as bssession = requests.session()post_url = ‘https://www.zhihu.com/#signin‘agent = ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/5.1.2.3000 Chrome/55.0.2883.75 Safari/537.36‘headers = { "Host": "www.zhihu.com", "Referer":"http://www.zhihu.com/", ‘User-Agent‘:agent}postdata = { ‘password‘: ‘*****‘, ‘account‘: ‘******‘,}response = bs(requests.get(‘http://www.zhihu.com/#signin‘,headers=headers).content, ‘html.parser‘)xsrf = response.find(‘input‘,attrs={‘name‘:‘_xsrf‘})[‘value‘]postdata[‘_xsrf‘] =xsrfresponed = session.post(‘http://www.zhihu.com/login/email‘,headers=headers,data=postdata)print(responed)
結果顯示:
<Response [200]>;
代碼做一些修改:
import requests
from bs4 import BeautifulSoup
session = requests.session()
agent = ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/5.1.2.3000 Chrome/55.0.2883.75 Safari/537.36‘
headers = {
"Host": "www.zhihu.com",
"Origin":"https://www.zhihu.com/",
"Referer":"http://www.zhihu.com/",
‘User-Agent‘:agent
}
postdata = {
‘password‘: ‘*****‘,
‘account‘: ‘******‘,
}
response = session.get("https://www.zhihu.com", headers=headers)
soup = BeautifulSoup(response.content, "html.parser")
xsrf = soup.find(‘input‘, attrs={"name": "_xsrf"}).get("value")
postdata[‘_xsrf‘] =xsrf
login_page = session.post(‘http://www.zhihu.com/login/email‘, data=postdata, headers=headers)
print(login_page.status_code)
運行結果:200
代表響應的狀態為請求成功,可以成功登入表單。
python爬蟲--類比登入知乎