- Notifications
You must be signed in to change notification settings - Fork64
andybalholm/cascadia
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The Cascadia package implements CSS selectors for use with the parse trees produced by the html package.
To test CSS selectors without writing Go code, check outcascadia the command line tool, a thin wrapper around this package.
The following is an example of how you can use Cascadia.
package mainimport ("fmt""log""strings""github.com/andybalholm/cascadia""golang.org/x/net/html")varpricingHtmlstring=`<div><div><h4>Free</h4></div><div><h1>$0/mo</h1><ul><li>10 users included</li><li>2 GB of storage</li><li><a href="https://example.com">See more</a></li></ul></div></div><div><div><h4>Pro</h4></div><div><h1>$15/mo</h1><ul><li>20 users included</li><li>10 GB of storage</li><li><a href="https://example.com">See more</a></li></ul></div></div><div><div><h4>Enterprise</h4></div><div><h1>$29/mo</h1><ul><li>30 users included</li><li>15 GB of storage</li><li><a>See more</a></li></ul></div></div>`funcQuery(n*html.Node,querystring)*html.Node {sel,err:=cascadia.Parse(query)iferr!=nil {return&html.Node{}}returncascadia.Query(n,sel)}funcQueryAll(n*html.Node,querystring) []*html.Node {sel,err:=cascadia.Parse(query)iferr!=nil {return []*html.Node{}}returncascadia.QueryAll(n,sel)}funcAttrOr(n*html.Node,attrName,orstring)string {for_,a:=rangen.Attr {ifa.Key==attrName {returna.Val}}returnor}funcmain() {doc,err:=html.Parse(strings.NewReader(pricingHtml))iferr!=nil {log.Fatal(err)}fmt.Printf("List of pricing plans:\n\n")fori,p:=rangeQueryAll(doc,"div.card.mb-4.box-shadow") {planName:=Query(p,"h4").FirstChild.Dataprice:=Query(p,".pricing-card-title").FirstChild.DatausersIncluded:=Query(p,"li:first-child").FirstChild.Datastorage:=Query(p,"li:nth-child(2)").FirstChild.DatadetailsUrl:=AttrOr(Query(p,"li:last-child a"),"href","(No link available)")fmt.Printf("Plan #%d\nName: %s\nPrice: %s\nUsers: %s\nStorage: %s\nDetails: %s\n\n",i+1,planName,price,usersIncluded,storage,detailsUrl,)}}
The output is:
List of pricing plans:Plan #1Name: FreePrice: $0/moUsers: 10 users includedStorage: 2 GB of storageDetails: https://example.comPlan #2Name: ProPrice: $15/moUsers: 20 users includedStorage: 10 GB of storageDetails: https://example.comPlan #3Name: EnterprisePrice: $29/moUsers: 30 users includedStorage: 15 GB of storageDetails: (No link available)
About
CSS selector library in Go
Resources
License
Stars
Watchers
Forks
Packages0
No packages published