標籤:python 爬蟲 Regex sublime text2
最近接觸Python爬蟲,以爬取學校新聞網新聞標題、日期、點擊量為例,記錄一下工作進度
目前,感覺Python爬蟲的過程無非兩步:
Step1.擷取網頁url(利用Python庫函數import urllib2)
Step2.利用Regex對html中的字串進行匹配、尋找等操作
自我感覺sublime text2編輯器真心好用,部署Python後不會像WingIDE、notepad++那樣存在那麼多頭疼的小問題,推薦使用
學校新聞網:西南交通大學新聞網--交大新聞
# -*- coding: UTF-8 -*- import urllib2import sysimport reimport os#***********fuction define************#def extract_url(info): rege="<li><span class=\"title\"><a href=\"(.*?)\">"#fei tan lan mo shi re_url = re.findall(rege, info) n=len(re_url) for i in range(0,n): re_url[i]="http://news.swjtu.edu.cn/"+re_url[i] return re_urldef extract_title(sub_web): re_key = "<h4>\r\n (.*)\r\n </h4>" title = re.findall(re_key,sub_web) return titledef extract_date(sub_web): re_key = "日期:(.*?) " date = re.findall(re_key,sub_web) return datedef extract_counts(sub_web): re_key = "點擊數:(.*?) " counts = re.findall(re_key,sub_web) return counts #*************main**************#fp=open('output.txt','w')content = urllib2.urlopen('http://news.swjtu.edu.cn/ShowList-82-0-1.shtml').read()url=extract_url(content)string=""n=len(url)print nfor i in range(0,n): sub_web = urllib2.urlopen(url[i]).read() sub_title = extract_title(sub_web) string+=sub_title[0] string+=' ' sub_date = extract_date(sub_web) string+="日期:"+sub_date[0] string+=' ' sub_counts = extract_counts(sub_web) string+="點擊數:"+sub_counts[0] string+='\n' # print stringprint stringfp.close()
附:Python爬蟲學習系列教程
Python爬取新聞網標題、日期、點擊量