基於python的爬蟲(一)

來源:互聯網
上載者:User

標籤:order   列印   turn   user   ret   head   post   bsp   idt   

抓取網頁

python核心庫

urllib2

 

實現對靜態網頁的抓取,不得不說,“人生苦短,我用python”這句話還是有道理的,要是用java來寫,這估計得20行代碼

(對不住了部落格園了,就拿你開刀吧)

def staticFetch():    url = "http://www.cnblogs.com/"    request = urllib2.Request(url)    response = urllib2.urlopen(request)    print response.read()

 

實現對動態網頁的抓取,採用post請求,如果想用get方法,只需要把參數接在url後面,不需要data這個參數

def postFetch():    data = ‘Keywords:爬蟲‘    url = "http://zzk.cnblogs.com/s/blogpost?Keywords=%E7%88%AC%E8%99%AB"    request = urllib2.Request(url, data)    response = urllib2.urlopen(request)    print response.read()
匹配資料

Regex

解釋

案例(虛擬碼)

.*

貪婪模式,匹配除了分行符號之外的所有字元

str = abcbc

regex = a.*c

return abcbc

.*?

非貪婪模式

str = abcbc

regex = a.*c

return abc

(.*?)

表示只要匹配這一部分

如果是匹配多個則返回的是一個元群組類型

str = abcbc

regex = a(.*)c

return b

 more

 

 

 

偽造瀏覽器請求

urllib2.HTTPError: HTTP Error 403: Forbidden

當你在運行python的時候出現這個錯誤,則該網址設定過了禁止爬蟲訪問,需要偽裝一下http的要求標頭,加入如下代碼再運行就ok了。

head={‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘}urllib2.Request(url,headers=head)

 

網頁亂碼問題

看看爬下來的html是什麼編碼格式的

一般都是utf-8,也有gb2312和asic的,保證你的編碼和網頁的編碼是同一種編碼。

 

中文亂碼

如果爬下來的網頁列印的時候出現\xe6\x96\xb0\xe4\xba\xba這種資訊,你可以用以下語句轉換成字串查看

‘,‘.join(str)

 

參考資料

//一個python爬蟲從入門到放棄的好部落格

http://cuiqingcai.com/1052.html

基於python的爬蟲(一)

聯繫我們

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