兄弟连区块链培训Go语言爬虫编写由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“go语言区块链”。
兄弟连区块链培训Go语言爬虫编写
兄弟连教育建议,用户在考虑培训周期时要切实结合自身目前所掌握的区块链知识的多少、培训的目的是简单的认知提升还是借此高薪就业等等。兄弟连Go全栈与区块链培训课程设置为5个半月共计22周的学习时长,由浅入深进行讲解,助力于小白用户向区块链工程师的转型。
课程体系设计架构包括了区块链的基础语言Go语言、区块链后端技术体系、区块链公链、区块链分布式应用开发等内容讲解,以及到最后的面试指导和项目实战。课程由清华微软谷歌名师团队精心打造,历时半年时间共同研发而出。
上次用Scala写了个爬虫。最近在闲工夫之时,学习Go语言,便用Go移植了那个用Scala写的爬虫,代码如下: package main
import(“fmt”
“io/ioutil”
“net/http”
“regexp”)
var(ptnIndexItem
= regexp.MustCompile(`(.+)`)
ptnContentRough = regexp.MustCompile(`(?s).*(.*).*`)
ptnBrTag
= regexp.MustCompile(``)
ptnHTMLTag
= regexp.MustCompile(`(?s)`)
ptnSpace
= regexp.MustCompile(`(^s+)|()`))
func Get(url string)(content string, statusCode int){
resp, err1 := http.Get(url)
if err1!= nil {
statusCode =-100
return
}
defer resp.Body.Close()
data, err2 := ioutil.ReadAll(resp.Body)
if err2!= nil {
statusCode =-200
return
}
statusCode = resp.StatusCode
content = string(data)
return }
type IndexItem struct {
url
string
title string }
func findIndex(content string)(index []IndexItem, err error){
matches := ptnIndexItem.FindAllStringSubmatch(content, 10000)
index = make([]IndexItem, len(matches))
for i, item := range matches {
index[i] = IndexItem
}
return }
func readContent(url string)(content string){
raw, statusCode := Get(url)
if statusCode!= 200 {
fmt.Print(“Fail to get the raw data from”, url, “n”)
return
}
match := ptnContentRough.FindStringSubmatch(raw)
if match!= nil {
content = match[1]
} else {
return
}
content = ptnBrTag.ReplaceAllString(content, “rn”)
content = ptnHTMLTag.ReplaceAllString(content, “”)
content = ptnSpace.ReplaceAllString(content, “”)
return }
func main(){
fmt.Println(`Get index...`)
s, statusCode := Get
if statusCode!= 200 {
return
}
index, _ := findIndex(s)
fmt.Println(`Get contents and write to file...`)
for _, item := range index {
fmt.Printf(“Get content %s from %s and write to file.n”, item.title, item.url)
fileName := fmt.Sprintf(“%s.txt”, item.title)
content := readContent(item.url)
ioutil.WriteFile(fileName, []byte(content), 0644)
fmt.Printf(“Finish writing to %s.n”, fileName)
} }
代码行数比Scala版的有一定增加,主要原因有以下几方面原因:golang 重视代码书写规范,或者说代码格式,很多地方写法比较固定,甚至比较麻烦。比如就算是if判断为真后的执行语句只有一句话,按照代码规范,也要写出带大括号的三行,而在Scala和很多其他语言中,一行就行;golang 的strings包和regexp包提供的方法并不特别好用,特别是和Scala相比,使用起来感觉Scala的正则和字符串处理要舒服的多;scala版的爬虫里面用到了Scala标准库中的实用类和方法,它们虽然不是语法组成,但用起来感觉像是语法糖,这里很多方法和函数式编程有关,golang的函数式编程还没有去仔细学习。
当然golang版的爬虫也有一个优势,就是编译速度很快,执行速度在现在的写法里面体现不出优势;golang的特性goroutine在这里没有用到,这段代码今后会不断改进。