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


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 requests

conn = 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 requests

conn = 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM