爬蟲練手-豆瓣top250(go版以及python版)

weixin_33890499發表於2017-11-11

  最近學習go,就找了一個例子練習【go語言爬蟲】go語言爬取豆瓣電影top250,思路大概就是獲取網頁,然後根據頁面元素,用正規表示式匹配電影名稱、評分、評論人數。原文有個地方需要修改下<code>pattern4 := <img width="100" alt="(.*?)" src=</code>,這樣就能執行了

3962840-71876c4338284c6c.png
結果截圖

這個例子可以由修改下變成併發的形式,提高效能(參考golang 併發 chan

var sem chan int = make(chan int,10);
   for i := 0; i < 10; i++ {
       go func(i int) {
           header := map[string]string{
               "Host":                      "movie.douban.com",
               "Connection":                "keep-alive",
               "Cache-Control":             "max-age=0",
               "Upgrade-Insecure-Requests": "1",
               "User-Agent":                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
               "Accept":                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
               "Referer":                   "https://movie.douban.com/top250",
           }
           fmt.Println("正在抓取第" + strconv.Itoa(i) + "頁......")
           url := "https://movie.douban.com/top250?start=" + strconv.Itoa(i*25) + "&filter="
           spider := &Spider{url, header}
           html := spider.get_html_header()
           
           pattern2 := `<span>(.*?)評價</span>`
           rp2 := regexp.MustCompile(pattern2)
           find_txt2 := rp2.FindAllStringSubmatch(html, -1)
           
           pattern3 := `property="v:average">(.*?)</span>`
           rp3 := regexp.MustCompile(pattern3)
           find_txt3 := rp3.FindAllStringSubmatch(html, -1)

           
           pattern4 := `<img width="100" alt="(.*?)" src=`
           rp4 := regexp.MustCompile(pattern4)
           find_txt4 := rp4.FindAllStringSubmatch(html, -1)

           for i := 0; i < len(find_txt2); i++ {
               fmt.Printf("%s %s %s\n", find_txt4[i][1], find_txt3[i][1], find_txt2[i][1], )
               f.WriteString(find_txt4[i][1] + "\t" + find_txt3[i][1] + "\t" + find_txt2[i][1] + "\t" + "\r\n")

           }
           sem <- 0
       }(i)
   }
   for i := 0; i < 10; i++ { <-sem }
   close(sem)
3962840-f699438a84163ed0.png
併發效果截圖

  到這裡go爬蟲部分已經介紹完畢,百無聊賴之際又寫了一個python版,python果真是簡潔,最後祝大家買買買得開心

# coding=utf-8  #
import re
import urllib2
import datetime
def getDouban(i):
    print "爬取第" + str(i)+"頁"
    html = "https://movie.douban.com/top250?start=" + str(i) + "&filter="
    try:
        page = urllib2.urlopen(html, timeout=3)
        result = page.read()
        score = re.findall('property="v:average">(.*?)</span>',result)
        person = re.findall('<span>(.*?)評價</span>',result)
        name= re.findall('<img width="100" alt="(.*?)" src=', result)
        j=0
        while j<len(name):
            print name[j], score[j]+'分', person[j]
            j=j+1
    except:
        print i
starttime = datetime.datetime.now()
params=[]
for i in range(25):
    getDouban(i)
endtime = datetime.datetime.now()
print "爬蟲歷時"+str((endtime-starttime).seconds)+"s完成"
3962840-57ff5e6c339f8dfd.png
python版執行結果

相關文章