Python-爬蟲-requests庫用語post登入

來源:互聯網
上載者:User

標籤:ade   gecko   user   pre   zha   sub   cookie   傳遞   uga   

requests庫很強大,支援HTTP串連保持和串連池,支援使用cookie保持會話,支援檔案上傳,支援自動確定響應內容的編碼,支援國際化的URL和POST資料自動編碼。

可以發送無參數的get請求,也可以發送有參數的get請求,修改headers等等。

這裡主要展發送post請求,通過data參數來傳遞。

比如:登入chinaunix網站,通過登入名稱、密碼來登入。

通過查看chinaunix網站源碼,可以看到登入頁面的網址是:

http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LIcAc

不同的電腦登入網址可能不一樣,請查看具體的網頁原始碼。

為了應對網站的反爬蟲,可以修改headers來類比網頁登入。具體如下:

import requestsconn = requests.session()url = ‘http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LIcAc‘postdata = {    ‘username’:’***’,    ‘password’:’***‘}headers = {            ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36‘}rep = conn.post(url, data=postdata,headers=headers)with open(‘1.html‘, ‘wb‘) as f:    f.write(rep.content)

代碼中的登入名稱和密碼換成自己提前註冊好的,否則登入不上。

requests庫自動儲存cookie,不用再單獨設定。

import requestsconn = requests.session()url = ‘http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LIcAc‘postdata = {    ‘username‘:‘zhaoxn04‘,    ‘password‘:‘wobugaosuni2004‘}headers = {            ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36‘}rep = conn.post(url, data=postdata,headers=headers)with open(‘1.html‘, ‘wb‘) as f:    f.write(rep.content)url1 = ‘http://bbs.chinaunix.net/thread-4246512-1-1.html‘rep1 = conn.get(url1, headers=headers)with open(‘2.html‘, ‘wb‘) as f:    f.write(rep1.content)

 

Python-爬蟲-requests庫用語post登入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.