requests庫很強大,支持HTTP鏈接保持和鏈接池,支持使用cookie保持會話,支持文件上傳,支持自動肯定響應內容的編碼,支持國際化的URL和POST數據自動編碼。php
能夠發送無參數的get請求,也能夠發送有參數的get請求,修改headers等等。html
這裏主要展發送post請求,經過data參數來傳遞。python
好比:登陸chinaunix網站,經過登陸名、密碼來登陸。cookie
經過查看chinaunix網站源碼,能夠看到登陸頁面的網址是:session
http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LIcAcpost
不一樣的電腦登陸網址可能不同,請查看具體的網頁源代碼。網站
爲了應對網站的反爬蟲,能夠修改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)
代碼中的登陸名和密碼換成本身提早註冊好的,不然登陸不上。url
requests庫自動保存cookie,不用再單獨設置。.net
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)