只针对 <a href="www.xxxxx.com">链接进行抓取。
package main
import (
"fmt"
"runtime"
"log"
"net/http"
"math/rand"
"time"
"io/ioutil"
"regexp"
"strings"
"encoding/xml"
)
var urlchannel = make(chan string, 200) //channel中存入string类型的href属性,缓冲200
var atagRegExp = regexp.MustCompile(`<a[^>]+[(href)|(HREF)]\s*\t*\n*=\s*\t*\n*[(".+")|('.+')][^>]*>[^<]*</a>`) //以Must前缀的方法或函数都是必须保证一定能执行成功的,否则将引发一次panic
func main() {
//go spy("http://www.3qzone.com/")
go spy("http://www.qidian.com/")
for url := range urlchannel{
fmt.Println("routines num = ", runtime.NumGoroutine(), "chan len = ", len(urlchannel)) //通过runtime可以获取当前运行时的一些相关参数等
go spy(url)
}
fmt.Println("a")
}
//noinspection GoTypesCompatibility
func spy(url string) {
defer func() {
if r := recover(); r != nil{
log.Println("[E]", r)
}
}()
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", GetRandomUserAgent())
client := http.DefaultClient
res, e := client.Do(req)
if e != nil{
fmt.Errorf("Get请求%s返回错误:%s", url, e)
return
}
if res.StatusCode == 200{
body := res.Body
defer body.Close()
bodyByte, _ := ioutil.ReadAll(body)
resStr := string(bodyByte)
atag := atagRegExp.FindAllString(resStr, -1)
for _, a := range atag{
href, _ := GetHref(a)
if strings.Contains(href, "article/details/"){
fmt.Println("☆", href)
}else{
fmt.Println("□", href)
}
urlchannel <- href
}
}
}
func GetHref(atag string) (href, content string) {
inputReader := strings.NewReader(atag)
decoder := xml.NewDecoder(inputReader)
for t, err := decoder.Token(); err == nil; t, err = decoder.Token(){
switch token := t.(type) {
//处理元素开始(标签)
case xml.StartElement:
for _, attr := range token.Attr{
attrName := attr.Name.Local
attrValue := attr.Value
if(strings.EqualFold(attrName, "href") || strings.EqualFold(attrName, "HREF")){
href = attrValue
}
}
//处理元素开始(标签)
case xml.EndElement:
//元素字符数据(这来是元素的文本)
case xml.CharData:
content = string([]byte(token))
default:
href = ""
content = ""
}
}
return href, content
}
var userAgent = [...]string{
"Mozilla/5.0 (compatible, MSIE 10.0, Windows NT, DigExt)",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, 360SE)",
"Mozilla/4.0 (compatible, MSIE 8.0, Windows NT 6.0, Trident/4.0)",
"Mozilla/5.0 (compatible, MSIE 9.0, Windows NT 6.1, Trident/5.0,",
"Opera/9.80 (Windows NT 6.1, U, en) Presto/2.8.131 Version/11.11",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, TencentTraveler 4.0)",
"Mozilla/5.0 (Windows, U, Windows NT 6.1, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Macintosh, Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh, U, Intel Mac OS X 10_6_8, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Linux, U, Android 3.0, en-us, Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
"Mozilla/5.0 (iPad, U, CPU OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, Trident/4.0, SE 2.X MetaSr 1.0, SE 2.X MetaSr 1.0, .NET CLR 2.0.50727, SE 2.X MetaSr 1.0)",
"Mozilla/5.0 (iPhone, U, CPU iPhone OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"MQQBrowser/26 Mozilla/5.0 (Linux, U, Android 2.3.7, zh-cn, MB200 Build/GRJ22, CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
}
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
func GetRandomUserAgent() string {
return userAgent[r.Intn(len(userAgent))]
}
这是一个还算完整的程序。用来取得一个指定的网站的 href 地址集。
下面,我们来一步一步分解它。分布实现它。
因为需要同时下载多个网页,所以用到了 goroutine 和 channel。建立一个通道变量。
var urlchannel = make(chan string, 200) //多个页面要同时下载,需要使用 goroutine 和 channel
在主函数 main 中,起步从域名开始访问一个网站,并且最终要遍历网站内所有的链接地址。所以需要建立一个函数,以便在函数内完成遍历。这个函数我们取名 spy。于是在主函数中添加 spy 的 goroutine。
go spy("http://www.sohu.com")
同时建立 spy 函数。
func spy(url string) {
}
在 spy 内要实现,取得网址对应的网页,并且分析网页的的链接。把取得的页面信息或链接信息给入 urlchannel 通道。
在主函数中接收通道信息,利用 runtime 获取当前运行时的一些相关参数信息。
func main(){
...
for url := range urlchannel {
fmt.Println("routines num =", runtime.NumGoroutine(), "chan len =", len(urlchannel))
...
}
...
在 spy 函数中,使用 defer 延迟一个匿名函数做错误处理。
defer func() {
if r := recover(); r != nil{
log.Println("[E]", r)
}
}()
http get方式发送网络访问请求
req, _ := http.NewRequest("GET", url, nil)
为了模拟不同的客户端访问,建立一个 userAgent 数组,预存各种客户端环境,使用随机取用的方式发送网络请求。
var userAgent = [...]string{
"Mozilla/5.0 (compatible, MSIE 10.0, Windows NT, DigExt)",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, 360SE)",
"Mozilla/4.0 (compatible, MSIE 8.0, Windows NT 6.0, Trident/4.0)",
"Mozilla/5.0 (compatible, MSIE 9.0, Windows NT 6.1, Trident/5.0,",
"Opera/9.80 (Windows NT 6.1, U, en) Presto/2.8.131 Version/11.11",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, TencentTraveler 4.0)",
"Mozilla/5.0 (Windows, U, Windows NT 6.1, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Macintosh, Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh, U, Intel Mac OS X 10_6_8, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Linux, U, Android 3.0, en-us, Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
"Mozilla/5.0 (iPad, U, CPU OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, Trident/4.0, SE 2.X MetaSr 1.0, SE 2.X MetaSr 1.0, .NET CLR 2.0.50727, SE 2.X MetaSr 1.0)",
"Mozilla/5.0 (iPhone, U, CPU iPhone OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"MQQBrowser/26 Mozilla/5.0 (Linux, U, Android 2.3.7, zh-cn, MB200 Build/GRJ22, CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
}
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
func GetRandomUserAgent() string {
return userAgent[r.Intn(len(userAgent))]
}
设置请求信息的 Header 利用 GetRandomUserAgent 函数随机设置客户端。使用 Client.Do 方法提交客户端请求。
req.Header.Set("User-Agent", GetRandomUserAgent())
client := http.DefaultClient
res, e := client.Do(req)
根据 res 返回值,分析获取的内容。并将有用的内容返回给通道。
if res.StatusCode == 200{
body := res.Body
defer body.Close()
bodyByte, _ := ioutil.ReadAll(body)
resStr := string(bodyByte)
atag := atagRegExp.FindAllString(resStr, -1)
for _, a := range atag{
href, _ := GetHref(a)
if strings.Contains(href, "article/details/"){
fmt.Println("☆", href)
}else{
fmt.Println("□", href)
}
urlchannel <- href
}
}
其中的 resStr 是网页内容,而 GetHref 函数实现了对内容的分析,并返回链接和链接内容。
func GetHref(atag string) (href, content string) {
inputReader := strings.NewReader(atag)
decoder := xml.NewDecoder(inputReader)
for t, err := decoder.Token(); err == nil; t, err = decoder.Token(){
switch token := t.(type) {
//处理元素开始(标签)
case xml.StartElement:
for _, attr := range token.Attr{
attrName := attr.Name.Local
attrValue := attr.Value
if(strings.EqualFold(attrName, "href") || strings.EqualFold(attrName, "HREF")){
href = attrValue
}
}
//处理元素开始(标签)
case xml.EndElement:
//元素字符数据(这里是元素的文本)
case xml.CharData:
content = string([]byte(token))
default:
href = ""
content = ""
}
}
return href, content
}
如果你不想分析链接,也可以直接使用 resStr 作为通道的赋值。