首页 文章资讯内容详情

使用Go语言(golang)写个简单的爬虫

2026-06-01 4 花语

本文内容纲要:

上次用Scala写了个爬虫。最近在闲工夫之时,学习Go语言,便用Go移植了那个用Scala写的爬虫,代码如下:

packagemain import( "fmt" "io/ioutil" "net/http" "regexp" ) var( ptnIndexItem=regexp.MustCompile(`<atarget="_blank"href="(.+\.html)"title=".+">(.+)</a>`) ptnContentRough=regexp.MustCompile(`(?s).*<div class="artcontent">(.*)<divid="zhanwei">.*`) ptnBrTag=regexp.MustCompile(`<br>`) ptnHTMLTag=regexp.MustCompile(`(?s)</?.*?>`) ptnSpace=regexp.MustCompile(`(^\s+)|( )`) ) funcGet(urlstring)(contentstring,statusCodeint){ resp,err1:=http.Get(url) iferr1!=nil{ statusCode=-100 return } deferresp.Body.Close() data,err2:=ioutil.ReadAll(resp.Body) iferr2!=nil{ statusCode=-200 return } statusCode=resp.StatusCode content=string(data) return } typeIndexItemstruct{ urlstring titlestring } funcfindIndex(contentstring)(index[]IndexItem,errerror){ matches:=ptnIndexItem.FindAllStringSubmatch(content,10000) index=make([]IndexItem,len(matches)) fori,item:=rangematches{ index[i]=IndexItem{"http://www.yifan100.com"+item[1],item[2]} } return } funcreadContent(urlstring)(contentstring){ raw,statusCode:=Get(url) ifstatusCode!=200{ fmt.Print("Failtogettherawdatafrom",url,"\n") return } match:=ptnContentRough.FindStringSubmatch(raw) ifmatch!=nil{ content=match[1] }else{ return } content=ptnBrTag.ReplaceAllString(content,"\r\n") content=ptnHTMLTag.ReplaceAllString(content,"") content=ptnSpace.ReplaceAllString(content,"") return } funcmain(){ fmt.Println(`Getindex...`) s,statusCode:=Get("http://www.yifan100.com/dir/15136/") ifstatusCode!=200{ return } index,_:=findIndex(s) fmt.Println(`Getcontentsandwritetofile...`) for_,item:=rangeindex{ fmt.Printf("Getcontent%sfrom%sandwritetofile.\n",item.title,item.url) fileName:=fmt.Sprintf("%s.txt",item.title) content:=readContent(item.url) ioutil.WriteFile(fileName,[]byte(content),0644) fmt.Printf("Finishwritingto%s.\n",fileName) } }

代码行数比Scala版的有一定增加,主要原因有以下几方面原因:

1golang重视代码书写规范,或者说代码格式,很多地方写法比较固定,甚至比较麻烦。比如就算是if判断为真后的执行语句只有一句话,按照代码规范,也要写出带大括号的三行,而在Scala和很多其他语言中,一行就行;

2golang的strings包和regexp包提供的方法并不特别好用,特别是和Scala相比,使用起来感觉Scala的正则和字符串处理要舒服的多;

3scala版的爬虫里面用到了Scala标准库中的实用类和方法,它们虽然不是语法组成,但用起来感觉像是语法糖,这里很多方法和函数式编程有关,golang的函数式编程还没有去仔细学习。

当然golang版的爬虫也有一个优势,就是编译速度很快,执行速度在现在的写法里面体现不出优势;golang的特性goroutine在这里没有用到,这段代码今后会不断改进。

本文内容总结:

原文链接:https://www.cnblogs.com/tt-0411/archive/2013/03/13/2958130.html