Golang 網絡爬蟲框架gocolly/colly 五 獲取動態數據
gcocolly+goquery可以非常好地抓取HTML頁面中的數據,但碰到頁面是由Javascript動態生成時,用goquery就顯得捉襟見肘了。解決方法有很多種,一,最笨拙但有效的方法是字符串處理,go語言string底層對應字節數組,復制任何長度的字符串的開銷都很低廉,搜索性能比較高;二,利用正則表達式,要提取的數據往往有明顯的特征,所以正則表達式寫起來比較簡單,不必非常嚴謹;三,使用瀏覽器控件,比如webloop;四,直接操縱瀏覽器,比如chromedp。一和二需要goquery提取javascript,然后再提取數據,速度非常快;三和四不需要分析腳本,在瀏覽器執行JavaScript生成頁面后再提取,是比較偷懶的方式,但缺點是執行速度很慢,如果在腳本非常復雜、懶得分析腳本的情況下,犧牲下速度也是不錯的選擇。
不同的場景,做不同的選擇。中證指數有限公司下載中心提供了行業市盈率下載,數據文件的Url在頁面的腳本中,腳本簡單且特征明顯,直接用正則表達式的方式是最好的選擇。
 
下載地址對應一段腳本
<a href="javascript:;" class="ml-20 dl download1">下載<i class="i_icon i_icon_rar ml-5"></i></a>
<script> $(function() { //切換 $('.hysyl_con').rTabs({ bind: 'click', auto: false, }); tabs($('.snav .tab_item'),$('.sCon .tab-con-item')); tabs($('.snav2 .tab_item'),$('.sCon2 .tab-con-item')); tabs($('.snav3 .tab_item'),$('.sCon3 .tab-con-item')); $("#search_code1").on("click",function(){ var csrc_code = $("#csrc_code1").val(); if (csrc_code == '') { return false; } var url = "http://www.csindex.com.cn/zh-CN/downloads/industry-price-earnings-ratio-detail?date=2018-01-19&class=1&search=1&csrc_code="+csrc_code; $("#link_1").attr('href', url); document.getElementById("link_1").click(); }) $("#search_code2").on("click",function(){ var csrc_code = $("#csrc_code2").val(); if (csrc_code == '') { return false; } var url = "http://www.csindex.com.cn/zh-CN/downloads/industry-price-earnings-ratio-detail?date=2018-01-19&class=1&search=1&csrc_code="+csrc_code; $("#link_2").attr('href', url); document.getElementById("link_2").click(); }) }) $(".download1").on("click",function(){ var date = $(".date1").val(); date = date.replace(/\-/g, ''); if (date) { $("#link1").attr('href', 'http://115.29.204.48/syl/'+date+'.zip'); document.getElementById("link1").click(); } }); $(".download2").on("click",function(){ var date = $(".date2").val(); date = date.replace(/\-/g, ''); if (date) { $("#link2").attr('href', 'http://115.29.204.48/syl/csi'+date+'.zip'); document.getElementById("link2").click(); } }); $(".download3").on("click",function(){ var date = $(".date3").val(); date = date.replace(/\-/g, ''); if (date) { $("#link3").attr('href', 'http://115.29.204.48/syl/bk'+date+'.zip'); document.getElementById("link3").click(); } }); </script>
 
點擊下載時,為link1元素生成href屬性,然后點擊link1,這需要用gocolly+goquery提取date,然后獲取服務器地址http://115.29.204.48/,根據獲取文件的類型拼接字符串生成下載地址。
獲取交易日期
 sTime := ""
    var bodyData []byte
 
    c:= colly.NewCollector()
 
    c.OnResponse(func (resp *colly.Response) {
        bodyData = resp.Body
    })
 
    c.OnHTML("input[name=date]",func (el *colly.HTMLElement) {
        
        sTime = el.Attr("value")
   
    })
 
 
    err = c.Visit("http://www.csindex.com.cn/zh-CN/downloads/industry-price-earnings-ratio")
    if err != nil {
        return
    }
 
        
獲取文件服務器地址,下載zip文件
    htmlDoc,err := goquery.NewDocumentFromReader(bytes.NewReader(bodyData))
    if err != nil {
        return
    }
 
    scripts := htmlDoc.Find("script")
 
    destScript := ""
    for _,n := range scripts.Nodes {
        
 
        if n.FirstChild != nil {
 
            if strings.Contains(n.FirstChild.Data,"syl/csi") && strings.Contains(n.FirstChild.Data,".download2"){
                destScript = n.FirstChild.Data
                break
            }
        }
    }
 
    re,err := regexp.Compile("http://[0-9]+.[0-9]+.[0-9]+.[0-9]+/syl/csi")
    if err != nil {
        log.Fatal(err)
    }
    result := re.FindString(destScript)
  
    pos := strings.LastIndex(result,"/")
 
    parentUrl := result[0:pos+1]
 
    link := parentUrl
 
    sTime = strings.Replace(sTime,"-","",-1)
 
    fileName := ""
    if t == ZhengJjianHuiHangYePERatio {
        fileName = fmt.Sprintf("%s.zip",sTime)      
        link += fileName
        fileName = "zjh"+fileName
    }else if t == ZhongZhengHangYePERatio {
        fileName = fmt.Sprintf("csi%s.zip",sTime)
        link += fileName
        
    }else {
        fileName = fmt.Sprintf("bk%s.zip",sTime)
        link += fileName
    }
    
    fmt.Println(link)
    
    cli:=http.Client{}
    resp,err := cli.Get(link)
    if err != nil {
        return
    }
defer resp.Body.Close()
    fullFileName := fmt.Sprintf("%s/%s",filePath,fileName)
    if resp.StatusCode == 200 {
        
        allBody,err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return err
        }
 
        err = ioutil.WriteFile(fullFileName,allBody,0666)
        if err != nil {
            return err
        }
    }else{
        err = fmt.Errorf("bad resp.%d",resp.StatusCode)
        return 
    }
 
    err = archiver.Zip.Open(fullFileName, filePath)
 
        
在腳本里匹配服務器ip地址用 http://[0-9]+.[0-9]+.[0-9]+.[0-9]+/syl/csi
,因為前后都有限定元素,所以寫得比較簡單;如果沒有前后限定條件,設計正則表達式就得多費心了,復雜的正則表達式會嚇跑很多人。不過沒關系,稍微了解一些正則表達式的知識,就可以用在爬蟲上了。
下載的文件是excel(.xls格式)的zip壓縮包,解壓縮操縱及xls讀取后面再介紹。
轉載請注明出處:https://www.cnblogs.com/majianguo/
