天天看點

Python爬蟲入門_之urllib2&&urllib

####筆者是在python2.7環境下學習爬蟲的

import urllib2	#引入子產品
import urllib
html = urllib2.urlopen('http://www.jikexueyuan.com')
html.read()
           

以上幾行,簡單的把極客學院的html頁面爬下來了,分析一下urllib2子產品:

# urlopen()
>>> urllib2.urlopen(url, data, timeout) #第一個參數是打開的url,第二個是,将要傳入的參數
這裡涉及到用get/post方式請求打開url
>>> value = {'username':'root','password':123456}
>>> param = urllib.urlencode(value)
>>> print param
'username=root&password=123456'
>>> html = urllib2.urlopen('www.ccut.edu.cn?%s' % param) #以get方式請求
>>> html = urllib2.urlopen('www.ccut.edu.cn', param)#以post方式請求
>>> 
           
#urllib2.Request()可以用來設定代理防止反爬蟲
>>> user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  
>>> headers = { 'User-Agent' : user_agent }
>>> request = urllib2.Request(url, param, headers)#此處的url,param都同上
>>> response = urllib2.urlopen(request)
>>> response.read() #到此結束,重新定義了代理

           

代理設定:假如一個網站它會檢測某一段時間某個IP 的通路次數,如果通路次數過多,它會禁止你的通路。是以你可以設定一些代理伺服器來幫助你做工作,每隔一段時間換一個代理

enable_proxy = True
proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})
null_proxy_handler = urllib2.ProxyHandler({})
if enable_proxy:
    opener = urllib2.build_opener(proxy_handler)
else:
    opener = urllib2.build_opener(null_proxy_handler)
urllib2.install_opener(opener)
           

模拟登入:

#很多網頁需要登入才能看到我們想要抓取的内容,我們可以模拟登入這個過程,儲存cookie:
	 url = 'www.ccut.edu.cn'
	cookj = cookielib.CookieJar()
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookj))
	urllib2.install_opener(opener)
	response = urllib2.urlopen(url)
           

更多詳細請參考這篇文章http://cuiqingcai.com/954.html