爬蟲系列(2)-----python爬取CSDN部落格首頁所有文章

來源:互聯網
上載者:User

標籤:分享   wow   get   style   color   ror   code   retrieve   addheader   

對於Python初學者來說,爬蟲技能是應該是最好入門,也是最能夠有讓自己有成就感的,今天在整理代碼時,整理了一下之前自己學習爬蟲的一些代碼,今天上第2個簡單的例子,python爬取CSDN部落格首頁所有文章。廢話不多說,直接上代碼講解。

step1:開啟需要爬取的網站:79588126"對應的資訊就是該文章的網址,這樣就好辦了,就用簡單的正則匹配就可以了,下面開始進行爬取啦。

step3:代碼很短,就直接上代碼了啊!
import urllib.requestimport reurl=‘https://blog.csdn.net/‘#類比瀏覽器headers=("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.7 Safari/537.36")opener=urllib.request.build_opener()opener.addheaders=[headers]#添加前序urllib.request.install_opener(opener)#設定opner全域化#擷取網頁資訊data=urllib.request.urlopen(url).read().decode(‘utf-8‘)#設定正則pat=‘<a strategy=.*?href="(.*?)" target="_blank">‘#匹配正則res=re.compile(pat).findall(data)#儲存資料for i in range(len(res)):    try:        file="F:/csdn/"+str(i+1)+‘.html‘        urllib.request.urlretrieve(res[i],file)        print(‘第‘+str(i+1)+‘篇文章爬取成功!‘)    except urllib.error.URLError as e:        if hasattr(e,"code"):            print(e.code)        if hasattr(e,"reason"):            print(e.reason)

爬取的結果如下:

 

爬蟲系列(2)-----python爬取CSDN部落格首頁所有文章

聯繫我們

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