Python爬蟲的post請求簡單例項
阿新 • • 發佈:2019-02-14
登陸網頁註冊時用Python進行post請求,程式碼
首先檢視頁面原始碼,注意form表單部分,哪裡是需要遞交的表單資訊
執行程式碼
import urllib.request import urllib.parse url='http://www.iqianyue.com/mypost' postdata=urllib.parse.urlencode({'name':'chenkehk','pass':'316107'}).encode('utf-8')#用字典儲存索要註冊的資訊並用urlencode編碼,使用encode()設定utf-8編碼格式 r=urllib.request.Request(url,postdata) r.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')#模仿瀏覽器爬取,新增包頭資訊 data=urllib.request.urlopen(r).read() f=open('D:/AuI18N/1.html','wb') f.write(data) f.close()
成功爬取網頁並自動遞交表單資訊,完成post請求
關於代理伺服器的設定
可以到http://www.xicidaili.com/這個地方找
程式碼:
import urllib.request import urllib.parse def u(p_add,url): p=urllib.request.ProxyHandler({'http':p_add})#設定代理伺服器資訊, openr=urllib.request.build_opener(p,urllib.request.HTTPSHandler)#構造一個物件,引數是代理資訊和urllib.request.HTTPSHandler類 urllib.request.install_opener(openr)#建立全域性預設的openrd物件 data=urllib.request.urlopen(url).read().decode('utf-8')#開啟網址,爬取內容 return data p_add='111.155.116.240:8123' data=u(p_add,'http://www.baidu.com') print(len(data))
Debuglog日誌,在爬取網頁的同時列印除錯日誌,程式碼:
import urllib.request import urllib.parse httphd=urllib.request.HTTPHandler(debuglevel=1) httpshd=urllib.request.HTTPSHandler(debuglevel=1) openr=urllib.request.build_opener(httphd,httpshd) urllib.request.install_opener(openr) data=urllib.request.urlopen('http://edu.51cto.com')
如何查詢登陸介面的,使用者名稱密碼欄位,以下為例
在構造表單是可以建一個字典
{
"username":"chenkehao"
"password":"1111"
}
然後遞交表單即可