GO爬虫-爬取手机号

 

正则爬取手机号

结果:

代码:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "io/ioutil"
 6     "net/http"
 7     "os"
 8     "regexp"
 9 )
10 
11 var (
12     rePhone = `(1[3456789]\d)(\d{4})(\d{4})`
13 )
14 
15 func HandleError(err error, when string) {
16     if err != nil {
17         fmt.Println(when, err)
18         os.Exit(1)
19     }
20 }
21 
22 func main() {
23     //http get请求页面
24     resp, err := http.Get("https://www.haomagujia.com/")
25 
26     //处理报错
27     HandleError(err, "http.Get")
28 
29     //读取整体获取的页面内容
30     bytes, _ := ioutil.ReadAll(resp.Body)
31     html := string(bytes)
32     //fmt.Println(html)
33 
34     //使用正则表达式对象在网页中过滤出手机号信息
35     re := regexp.MustCompile(rePhone)
36     //-1 代表匹配全部
37     allString := re.FindAllStringSubmatch(html, -1)
38     for _, x := range allString {
39         fmt.Println(x)
40     }
41 
42 }

猜你喜欢

转载自www.cnblogs.com/chaoyangxu/p/12342678.html