標籤:分享 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部落格首頁所有文章