Google资深工程师深度讲解Go语言-单任务版爬虫(十四)

一.获得初始页面内容

gopm get -g -v golang.org/x/text  //引入gbk库

报错: bash: gopm: command not found
解决方法: 使用gopm 完成安装

gopm--Go Package Manager 的缩写。是go 上的包管理工具,十分好用。 gopm

1.gopm 安装:

这个十分简单只需一条命令就可以了:

go get -u github.com/gpmgo/gopm  //亲测可用

2.使用 gopm安装需要的包

gopm 具有丰富的包管理功能,具体的管理命令可以参考官方文档(官方文档有中文版 各位爽不爽)链接
这里只需要一条命令就可以搞定了:

gopm bin -d $GOPATH/bin PackageName

二.正则表达式获取邮件地址

package main

import (
	"fmt"
	"regexp"
)

const text = `
my email is [email protected]
email2 is [email protected]
email3 is [email protected]
`

func main() {
	re := regexp.MustCompile(`([a-zA-Z0-9]+)@([a-zA-Z0-9]+)(\.[a-zA-Z0-9]+)`)
	match := re.FindAllStringSubmatch(text, -1)
	for _, m := range match {
		fmt.Println(m)
	}
}

2.提取城市和url

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
)

func main() {
	resp, err := http.Get("http://www.zhenai.com/zhenghun")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		fmt.Println("Error:status code", resp.StatusCode)
		return
	}
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	//fmt.Printf("%s\n", all)
	printCityList(all)
}

func printCityList(contents []byte){
	re:=regexp.MustCompile(`<a href="(http://www.zhenai.com/zhenghun/[a-z0-9]+)"[^>]*>([^<]+)</a>`)
	match:=re.FindAllSubmatch(contents,-1)
	for _,m :=range match {
		//for _,sub:=range m {
		//	fmt.Printf("%s",sub)
		//}
		//fmt.Println()
		fmt.Printf("city: %s,  Url:%s \n",m[2],m[1])
	}

	fmt.Printf("matches found:%d\n",len(match))
}

猜你喜欢

转载自blog.csdn.net/lxw1844912514/article/details/108629822