• 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 lxw@qq.com
    email2 is aa@def.com
    email3 is bb@eft.com.cn
    `
    
    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))
    }

    赞赏码

    非学,无以致疑;非问,无以广识

  • 相关阅读:
    Django URL 命名空间
    数据库
    iOS之网络数据下载和JSON解析
    IOS之AFNetworking的使用
    IOS之网络数据下载和JSON解析
    IOS之XML解析
    iOS网络基础知识
    iOS开发--Block
    IOS开发——使用数据库
    IOS 开发下拉刷新和上拉加载更多
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15452712.html
Copyright © 2020-2023  润新知