python爬蟲--類比登入知乎

來源:互聯網
上載者:User

標籤:使用者   處理   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爬蟲--類比登入知乎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.