goquery php,golang:Goquery简单爬虫实例

Selection类型提供的方法,这些方法是页面解析最重要,最核心的方法

1)类似函数的位置操作

-Eq(index int) *Selection     //根据索引获取某个节点集

-  First() *Selection          //获取第一个子节点集

-  Last() *Selection         //获取最后一个子节点集

-  Next() *Selection         //获取下一个兄弟节点集

-  NextAll() *Selection      //获取后面所有兄弟节点集

-  Prev() *Selection         //前一个兄弟节点集

- Get(index int) *html.Node  //根据索引获取一个节点

- Index() int                //返回选择对象中第一个元素的位置

- Slice(start, end int) *Selection  //根据起始位置获取子节点集

2)扩大 Selection 集合(增加选择的节点)

-  Add(selector string) *Selection //将匹配到的节点添加当前节点集合中

-   AndSelf() *Selection    //将堆栈上的前一组元素添加到当前的

-    Union() *Selection    //which is an alias for AddSelection()

3)过滤方法,减少节点集合

-  End() *Selection

- Filter…()     //过滤

- Has…()

- Intersection()   //which is an alias of FilterSelection()

- Not…()

4)循环遍历选择的节点

-  Each(f func(int, *Selection)) *Selection //遍历

- EachWithBreak(f func(int, *Selection) bool) *Selection  //可中断遍历

- Map(f func(int, *Selection) string) (result []string)  //返回字符串数组

5)修改文档

- After…()            //在匹配元素之后追加元素

- Append…()         //将选择器指定的元素添加到匹配元素集合的每个元素的末尾

- Before…()          //在匹配元素之前追加元素

- Clone()             //创建匹配节点的副本

- Empty()            //清空子节点

- Prepend…()

- Remove…()

- ReplaceWith…()

- Unwrap()

- Wrap…()

- WrapAll…()

- WrapInner…()

6)检测或获取节点属性值

- Attr(), RemoveAttr(), SetAttr()  //获取,移除,设置属性的值

- AddClass(), HasClass(), RemoveClass(), ToggleClass()

- Html()  //获取该节点的html

- Length() //返回该Selection的元素个数

- Size(), which is an alias for Length()

- Text()  //获取该节点的文本值

7)查询或显示一个节点的身份

- Contains() //包含

- Is…()

8)在文档树之间来回跳转(常用的查找节点方法)

- Children…()

- Contents()

- Find…()

- Next…()

- Parent[s]…()

- Prev…()

- Siblings…()

操作实例:

func main(){

client := http.Client{}

req,_ := http.NewRequest("GET","http://www.xicidaili.com/wn/1",nil)

req.Header.Add("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79     Safari/537.36 Maxthon/5.2.3.1000")

resp,_ := client.Do(req)

doc,_ := goquery.NewDocumentFromReader(resp.Body)

log.Print(doc.Html())

doc.Find("tbody tr").Each(func(iint, selection *goquery.Selection) {

proxy := models.TbSpiderProxyIp{}

selection.Children().Each(func(iint, selection *goquery.Selection) {

switch i {

case 1:

proxy.Ip = selection.Text()

case 2:

port, _ :=strconv.ParseInt(selection.Text(), 10, 64)

proxy.Port = port

case 3:

proxy.Address = selection.Text()

case 9:

proxy.Check_date = selection.Text()

default:

}

})

proxy.Https =1

proxy.Status =1

proxy.Createdate = time.Now().Format("2006-01-02 15:04:05")

models.InsertTbSpiderProxy(&proxy)

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值