Golang http

Golang http

  • 通用方法

    func HandleError(err error, reason string) {
    	if err != nil {
    		println(err, reason)
    	}
    }
    func getContentByUrl(url string) string{
    	resp, err := http.Get(url)
    	defer resp.Body.Close()
    	HandleError(err,"获取网站内容失败")
    	content, err := ioutil.ReadAll(resp.Body)
    	HandleError(err,"读取内容失败")
    	return string(content)
    }
    
  • 爬取邮箱

    //这里尽量不要使用^ $匹配字符串开始和结束的位置, 因为按照一行一行输出
    //匹配邮箱,\w == [0-9A-Za-z_]
    //这里需要使用反引号
    emailPattern = `\w+@\w+\.\w+`
    //获取邮箱
    func getEmail(content string){
    	regex := regexp.MustCompile(emailPattern)
    	//只会获取最左边第一个匹配的内容,包括子匹配内容
    	//regex.FindStringSubmatch()
    	//-1表示获取所有内容, 包括子匹配内容,通过下标获取子匹配
    	res := regex.FindAllStringSubmatch(content, -1)
    	for _, val := range res {
    		fmt.Println("email:",val)
    	}
    }
    func main() {
    	data := getContentByUrl("https://tieba.baidu.com/p/6826194469")
    	getEmail(data)
    	
    }
    
  • 爬取手机号

    //34578中的一个
    phonePattern = `1[34578]\d{9}`
    //获取电话号码
    func getPhone(content string){
    	regex := regexp.MustCompile(phonePattern)
    	res := regex.FindAllStringSubmatch(content, -1)
    	for _, val := range res {
    		fmt.Println("phone:",val)
    	}
    }
    func main() {
    	data := getContentByUrl("http://www.114best.com/")
    	getPhone(data)
    }
    
  • 爬取超链接

    //\w不包括.
    hrefPattern = `http(s)?://\w+\.\w+(\.\w+)?`
    //获取超链接文本
    func getLink(content string){
    	regex := regexp.MustCompile(hrefPattern)
    	res := regex.FindAllStringSubmatch(content, -1)
    	for _, val := range res {
    		//这里只获取第零个,不用获取()内的子表达式
    		fmt.Println("href:", val[0])
    	}
    }
    func main() {
    	data := getContentByUrl("http://www.114best.com/")
    	getLink(data)
    }
    
  • 爬取身份证

    //区号[1-9]\d{5}
    //年(18|19|20|)\d{2}
    //月((0[1-9])|(1[0-2]))
    //日(([0-2][1-9])|10|20|30|31)
    //校验码\d{3}[\dXx]
    IdentityCardPattern =`[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]`
    //获取身份证
    func getIdentityCard(content string){
    	regex := regexp.MustCompile(IdentityCardPattern)
    	res := regex.FindAllStringSubmatch(content, -1)
    	for _, val := range res {
    		fmt.Println("IdentityCard:", val[0])
    	}
    }
    func main() {
    		data := getContentByUrl("http://www.pinlue.com/article/2018/09/0801/306984954623.html")
    	getIdentityCard(data)
    }
    
posted @ 2020-08-18 18:27  CyberPelican  阅读(118)  评论(0编辑  收藏  举报