Go spider with x/net/html package

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

See many spider versions on the web, almost all using regexp Kanemasa match implementation.

Actually use Doc for better performance and more elegance

 PackageMainImport("FMT""Net/http""OS""Golang.org/x/net/html")funcVisit(Links []string, N *html. Node) []string{offN.type = = html.Elementnode&& N.data = =' A '{ for_, A: =Rangen.attr {ifA.key = ="href"{links =Append(Links, A.val)}}} forc: = N.firstchild; c! =Nil; c = c.nextsibling {links =Visit(Links, c)}returnLinksfuncMain() { for_, URL: =RangeOs. args[1:] {Links, ERR: =FindLinks(URL)ifErr! =Nil{FMT.fprintf(OS. Stderr, "FINDLINKS2:%v\n", ErrContinue      } for_, Link: =RangeLinks {fmt.Println(link)} }}funcFindLinks(URLstring) ([]string, Error) {RESP, ERR: = http.Get(URL)ifErr! =Nil{returnNil, ERR}ifResp. StatusCode! = http.Statusok{resp. Body.Close()returnNil, Fmt.Errorf("Getting%s:%s", Url, Resp. Status)} doc, ERR: = HTML.Parse(resp. Body) resp. Body.Close()ifErr! =Nil{returnNil, Fmt.Errorf("Pax resing%s as HTML:%v", wr., ERR)}returnVisit(Nil, Doc, Nil}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.