Python爬取新聞網標題、日期、點擊量

來源:互聯網
上載者:User

標籤: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爬取新聞網標題、日期、點擊量

聯繫我們

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