Best K6 code snippet using html.Matches
selector.go
Source:selector.go
1package cascadia23import (4 "bytes"5 "fmt"6 "regexp"7 "strings"89 "golang.org/x/net/html"10)1112// the Selector type, and functions for creating them1314// A Selector is a function which tells whether a node matches or not.15type Selector func(*html.Node) bool1617// hasChildMatch returns whether n has any child that matches a.18func hasChildMatch(n *html.Node, a Selector) bool {19 for c := n.FirstChild; c != nil; c = c.NextSibling {20 if a(c) {21 return true22 }23 }24 return false25}2627// hasDescendantMatch performs a depth-first search of n's descendants,28// testing whether any of them match a. It returns true as soon as a match is29// found, or false if no match is found.30func hasDescendantMatch(n *html.Node, a Selector) bool {31 for c := n.FirstChild; c != nil; c = c.NextSibling {32 if a(c) || (c.Type == html.ElementNode && hasDescendantMatch(c, a)) {33 return true34 }35 }36 return false37}3839// Compile parses a selector and returns, if successful, a Selector object40// that can be used to match against html.Node objects.41func Compile(sel string) (Selector, error) {42 p := &parser{s: sel}43 compiled, err := p.parseSelectorGroup()44 if err != nil {45 return nil, err46 }4748 if p.i < len(sel) {49 return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)50 }5152 return compiled, nil53}5455// MustCompile is like Compile, but panics instead of returning an error.56func MustCompile(sel string) Selector {57 compiled, err := Compile(sel)58 if err != nil {59 panic(err)60 }61 return compiled62}6364// MatchAll returns a slice of the nodes that match the selector,65// from n and its children.66func (s Selector) MatchAll(n *html.Node) []*html.Node {67 return s.matchAllInto(n, nil)68}6970func (s Selector) matchAllInto(n *html.Node, storage []*html.Node) []*html.Node {71 if s(n) {72 storage = append(storage, n)73 }7475 for child := n.FirstChild; child != nil; child = child.NextSibling {76 storage = s.matchAllInto(child, storage)77 }7879 return storage80}8182// Match returns true if the node matches the selector.83func (s Selector) Match(n *html.Node) bool {84 return s(n)85}8687// MatchFirst returns the first node that matches s, from n and its children.88func (s Selector) MatchFirst(n *html.Node) *html.Node {89 if s.Match(n) {90 return n91 }9293 for c := n.FirstChild; c != nil; c = c.NextSibling {94 m := s.MatchFirst(c)95 if m != nil {96 return m97 }98 }99 return nil100}101102// Filter returns the nodes in nodes that match the selector.103func (s Selector) Filter(nodes []*html.Node) (result []*html.Node) {104 for _, n := range nodes {105 if s(n) {106 result = append(result, n)107 }108 }109 return result110}111112// typeSelector returns a Selector that matches elements with a given tag name.113func typeSelector(tag string) Selector {114 tag = toLowerASCII(tag)115 return func(n *html.Node) bool {116 return n.Type == html.ElementNode && n.Data == tag117 }118}119120// toLowerASCII returns s with all ASCII capital letters lowercased.121func toLowerASCII(s string) string {122 var b []byte123 for i := 0; i < len(s); i++ {124 if c := s[i]; 'A' <= c && c <= 'Z' {125 if b == nil {126 b = make([]byte, len(s))127 copy(b, s)128 }129 b[i] = s[i] + ('a' - 'A')130 }131 }132133 if b == nil {134 return s135 }136137 return string(b)138}139140// attributeSelector returns a Selector that matches elements141// where the attribute named key satisifes the function f.142func attributeSelector(key string, f func(string) bool) Selector {143 key = toLowerASCII(key)144 return func(n *html.Node) bool {145 if n.Type != html.ElementNode {146 return false147 }148 for _, a := range n.Attr {149 if a.Key == key && f(a.Val) {150 return true151 }152 }153 return false154 }155}156157// attributeExistsSelector returns a Selector that matches elements that have158// an attribute named key.159func attributeExistsSelector(key string) Selector {160 return attributeSelector(key, func(string) bool { return true })161}162163// attributeEqualsSelector returns a Selector that matches elements where164// the attribute named key has the value val.165func attributeEqualsSelector(key, val string) Selector {166 return attributeSelector(key,167 func(s string) bool {168 return s == val169 })170}171172// attributeNotEqualSelector returns a Selector that matches elements where173// the attribute named key does not have the value val.174func attributeNotEqualSelector(key, val string) Selector {175 key = toLowerASCII(key)176 return func(n *html.Node) bool {177 if n.Type != html.ElementNode {178 return false179 }180 for _, a := range n.Attr {181 if a.Key == key && a.Val == val {182 return false183 }184 }185 return true186 }187}188189// attributeIncludesSelector returns a Selector that matches elements where190// the attribute named key is a whitespace-separated list that includes val.191func attributeIncludesSelector(key, val string) Selector {192 return attributeSelector(key,193 func(s string) bool {194 for s != "" {195 i := strings.IndexAny(s, " \t\r\n\f")196 if i == -1 {197 return s == val198 }199 if s[:i] == val {200 return true201 }202 s = s[i+1:]203 }204 return false205 })206}207208// attributeDashmatchSelector returns a Selector that matches elements where209// the attribute named key equals val or starts with val plus a hyphen.210func attributeDashmatchSelector(key, val string) Selector {211 return attributeSelector(key,212 func(s string) bool {213 if s == val {214 return true215 }216 if len(s) <= len(val) {217 return false218 }219 if s[:len(val)] == val && s[len(val)] == '-' {220 return true221 }222 return false223 })224}225226// attributePrefixSelector returns a Selector that matches elements where227// the attribute named key starts with val.228func attributePrefixSelector(key, val string) Selector {229 return attributeSelector(key,230 func(s string) bool {231 if strings.TrimSpace(s) == "" {232 return false233 }234 return strings.HasPrefix(s, val)235 })236}237238// attributeSuffixSelector returns a Selector that matches elements where239// the attribute named key ends with val.240func attributeSuffixSelector(key, val string) Selector {241 return attributeSelector(key,242 func(s string) bool {243 if strings.TrimSpace(s) == "" {244 return false245 }246 return strings.HasSuffix(s, val)247 })248}249250// attributeSubstringSelector returns a Selector that matches nodes where251// the attribute named key contains val.252func attributeSubstringSelector(key, val string) Selector {253 return attributeSelector(key,254 func(s string) bool {255 if strings.TrimSpace(s) == "" {256 return false257 }258 return strings.Contains(s, val)259 })260}261262// attributeRegexSelector returns a Selector that matches nodes where263// the attribute named key matches the regular expression rx264func attributeRegexSelector(key string, rx *regexp.Regexp) Selector {265 return attributeSelector(key,266 func(s string) bool {267 return rx.MatchString(s)268 })269}270271// intersectionSelector returns a selector that matches nodes that match272// both a and b.273func intersectionSelector(a, b Selector) Selector {274 return func(n *html.Node) bool {275 return a(n) && b(n)276 }277}278279// unionSelector returns a selector that matches elements that match280// either a or b.281func unionSelector(a, b Selector) Selector {282 return func(n *html.Node) bool {283 return a(n) || b(n)284 }285}286287// negatedSelector returns a selector that matches elements that do not match a.288func negatedSelector(a Selector) Selector {289 return func(n *html.Node) bool {290 if n.Type != html.ElementNode {291 return false292 }293 return !a(n)294 }295}296297// writeNodeText writes the text contained in n and its descendants to b.298func writeNodeText(n *html.Node, b *bytes.Buffer) {299 switch n.Type {300 case html.TextNode:301 b.WriteString(n.Data)302 case html.ElementNode:303 for c := n.FirstChild; c != nil; c = c.NextSibling {304 writeNodeText(c, b)305 }306 }307}308309// nodeText returns the text contained in n and its descendants.310func nodeText(n *html.Node) string {311 var b bytes.Buffer312 writeNodeText(n, &b)313 return b.String()314}315316// nodeOwnText returns the contents of the text nodes that are direct317// children of n.318func nodeOwnText(n *html.Node) string {319 var b bytes.Buffer320 for c := n.FirstChild; c != nil; c = c.NextSibling {321 if c.Type == html.TextNode {322 b.WriteString(c.Data)323 }324 }325 return b.String()326}327328// textSubstrSelector returns a selector that matches nodes that329// contain the given text.330func textSubstrSelector(val string) Selector {331 return func(n *html.Node) bool {332 text := strings.ToLower(nodeText(n))333 return strings.Contains(text, val)334 }335}336337// ownTextSubstrSelector returns a selector that matches nodes that338// directly contain the given text339func ownTextSubstrSelector(val string) Selector {340 return func(n *html.Node) bool {341 text := strings.ToLower(nodeOwnText(n))342 return strings.Contains(text, val)343 }344}345346// textRegexSelector returns a selector that matches nodes whose text matches347// the specified regular expression348func textRegexSelector(rx *regexp.Regexp) Selector {349 return func(n *html.Node) bool {350 return rx.MatchString(nodeText(n))351 }352}353354// ownTextRegexSelector returns a selector that matches nodes whose text355// directly matches the specified regular expression356func ownTextRegexSelector(rx *regexp.Regexp) Selector {357 return func(n *html.Node) bool {358 return rx.MatchString(nodeOwnText(n))359 }360}361362// hasChildSelector returns a selector that matches elements363// with a child that matches a.364func hasChildSelector(a Selector) Selector {365 return func(n *html.Node) bool {366 if n.Type != html.ElementNode {367 return false368 }369 return hasChildMatch(n, a)370 }371}372373// hasDescendantSelector returns a selector that matches elements374// with any descendant that matches a.375func hasDescendantSelector(a Selector) Selector {376 return func(n *html.Node) bool {377 if n.Type != html.ElementNode {378 return false379 }380 return hasDescendantMatch(n, a)381 }382}383384// nthChildSelector returns a selector that implements :nth-child(an+b).385// If last is true, implements :nth-last-child instead.386// If ofType is true, implements :nth-of-type instead.387func nthChildSelector(a, b int, last, ofType bool) Selector {388 return func(n *html.Node) bool {389 if n.Type != html.ElementNode {390 return false391 }392393 parent := n.Parent394 if parent == nil {395 return false396 }397398 if parent.Type == html.DocumentNode {399 return false400 }401402 i := -1403 count := 0404 for c := parent.FirstChild; c != nil; c = c.NextSibling {405 if (c.Type != html.ElementNode) || (ofType && c.Data != n.Data) {406 continue407 }408 count++409 if c == n {410 i = count411 if !last {412 break413 }414 }415 }416417 if i == -1 {418 // This shouldn't happen, since n should always be one of its parent's children.419 return false420 }421422 if last {423 i = count - i + 1424 }425426 i -= b427 if a == 0 {428 return i == 0429 }430431 return i%a == 0 && i/a >= 0432 }433}434435// simpleNthChildSelector returns a selector that implements :nth-child(b).436// If ofType is true, implements :nth-of-type instead.437func simpleNthChildSelector(b int, ofType bool) Selector {438 return func(n *html.Node) bool {439 if n.Type != html.ElementNode {440 return false441 }442443 parent := n.Parent444 if parent == nil {445 return false446 }447448 if parent.Type == html.DocumentNode {449 return false450 }451452 count := 0453 for c := parent.FirstChild; c != nil; c = c.NextSibling {454 if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {455 continue456 }457 count++458 if c == n {459 return count == b460 }461 if count >= b {462 return false463 }464 }465 return false466 }467}468469// simpleNthLastChildSelector returns a selector that implements470// :nth-last-child(b). If ofType is true, implements :nth-last-of-type471// instead.472func simpleNthLastChildSelector(b int, ofType bool) Selector {473 return func(n *html.Node) bool {474 if n.Type != html.ElementNode {475 return false476 }477478 parent := n.Parent479 if parent == nil {480 return false481 }482483 if parent.Type == html.DocumentNode {484 return false485 }486487 count := 0488 for c := parent.LastChild; c != nil; c = c.PrevSibling {489 if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {490 continue491 }492 count++493 if c == n {494 return count == b495 }496 if count >= b {497 return false498 }499 }500 return false501 }502}503504// onlyChildSelector returns a selector that implements :only-child.505// If ofType is true, it implements :only-of-type instead.506func onlyChildSelector(ofType bool) Selector {507 return func(n *html.Node) bool {508 if n.Type != html.ElementNode {509 return false510 }511512 parent := n.Parent513 if parent == nil {514 return false515 }516517 if parent.Type == html.DocumentNode {518 return false519 }520521 count := 0522 for c := parent.FirstChild; c != nil; c = c.NextSibling {523 if (c.Type != html.ElementNode) || (ofType && c.Data != n.Data) {524 continue525 }526 count++527 if count > 1 {528 return false529 }530 }531532 return count == 1533 }534}535536// inputSelector is a Selector that matches input, select, textarea and button elements.537func inputSelector(n *html.Node) bool {538 return n.Type == html.ElementNode && (n.Data == "input" || n.Data == "select" || n.Data == "textarea" || n.Data == "button")539}540541// emptyElementSelector is a Selector that matches empty elements.542func emptyElementSelector(n *html.Node) bool {543 if n.Type != html.ElementNode {544 return false545 }546547 for c := n.FirstChild; c != nil; c = c.NextSibling {548 switch c.Type {549 case html.ElementNode, html.TextNode:550 return false551 }552 }553554 return true555}556557// descendantSelector returns a Selector that matches an element if558// it matches d and has an ancestor that matches a.559func descendantSelector(a, d Selector) Selector {560 return func(n *html.Node) bool {561 if !d(n) {562 return false563 }564565 for p := n.Parent; p != nil; p = p.Parent {566 if a(p) {567 return true568 }569 }570571 return false572 }573}574575// childSelector returns a Selector that matches an element if576// it matches d and its parent matches a.577func childSelector(a, d Selector) Selector {578 return func(n *html.Node) bool {579 return d(n) && n.Parent != nil && a(n.Parent)580 }581}582583// siblingSelector returns a Selector that matches an element584// if it matches s2 and in is preceded by an element that matches s1.585// If adjacent is true, the sibling must be immediately before the element.586func siblingSelector(s1, s2 Selector, adjacent bool) Selector {587 return func(n *html.Node) bool {588 if !s2(n) {589 return false590 }591592 if adjacent {593 for n = n.PrevSibling; n != nil; n = n.PrevSibling {594 if n.Type == html.TextNode || n.Type == html.CommentNode {595 continue596 }597 return s1(n)598 }599 return false600 }601602 // Walk backwards looking for element that matches s1603 for c := n.PrevSibling; c != nil; c = c.PrevSibling {604 if s1(c) {605 return true606 }607 }608609 return false610 }611}612613// rootSelector implements :root614func rootSelector(n *html.Node) bool {615 if n.Type != html.ElementNode {616 return false617 }618 if n.Parent == nil {619 return false620 }621 return n.Parent.Type == html.DocumentNode622}
...
Matches
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v6 os.Exit(1)7 }8 for _, link := range visit(nil, doc) {9 fmt.Println(link)10 }11}12func visit(links []string, n *html.Node) []string {13 if n.Type == html.ElementNode && n.Data == "a" {14 for _, a := range n.Attr {15 if a.Key == "href" {16 links = append(links, a.Val)17 }18 }19 }20 for c := n.FirstChild; c != nil; c = c.NextSibling {21 links = visit(links, c)22 }23}
Matches
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v6 os.Exit(1)7 }8 for _, link := range visit(nil, doc) {9 fmt.Println(link)10 }11}12func visit(links []string, n *html.Node) []string {13 if n.Type == html.ElementNode && n.Data == "a" {14 for _, a := range n.Attr {15 if a.Key == "href" {16 links = append(links, a.Val)17 }18 }19 }20 for c := n.FirstChild; c != nil; c = c.NextSibling {21 links = visit(links, c)22 }23}24import (25func main() {26 doc, err := html.Parse(os.Stdin)27 if err != nil {28 fmt.Fprintf(os.Stderr, "findlinks1: %v29 os.Exit(1)30 }31 for _, link := range visit(nil, doc) {32 fmt.Println(link)33 }34}35func visit(links []string, n *html.Node) []string {36 if n.Type == html.ElementNode && n.Data == "a" {37 for _, a := range n.Attr {38 if a.Key == "href" {39 links = append(links, a.Val)40 }41 }42 }43 for c := n.FirstChild; c != nil; c = c.NextSibling {44 links = visit(links, c)45 }46}
Matches
Using AI Code Generation
1import (2func main() {3 for _, url := range os.Args[1:] {4 resp, err := http.Get(url)5 if err != nil {6 fmt.Fprintf(os.Stderr, "fetch: %v7 os.Exit(1)8 }9 doc, err := html.Parse(resp.Body)10 resp.Body.Close()11 if err != nil {12 fmt.Fprintf(os.Stderr, "findlinks1: %v13 os.Exit(1)14 }15 for _, link := range visit(nil, doc) {16 fmt.Println(link)17 }18 }19}20func visit(links []string, n *html.Node) []string {21 if n.Type == html.ElementNode && n.Data == "a" {22 for _, a := range n.Attr {23 if a.Key == "href" {24 links = append(links, a.Val)25 }26 }27 }28 for c := n.FirstChild; c != nil; c = c.NextSibling {29 links = visit(links, c)30 }31}
Matches
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println(err)10 }11 doc, err := html.Parse(strings.NewReader(string(body)))12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(html.Render(doc))16 fmt.Println("---------------------------------------------------")17 for _, link := range visit(nil, doc) {18 fmt.Println(link)19 }20}21func visit(links []string, n *html.Node) []string {22 if n.Type == html.ElementNode && n.Data == "a" {23 for _, a := range n.Attr {24 if a.Key == "href" {25 links = append(links, a.Val)26 }27 }28 }29 for c := n.FirstChild; c != nil; c = c.NextSibling {30 links = visit(links, c)31 }32}
Matches
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println(err)10 }11 re := regexp.MustCompile("<title>(.*)</title>")12 matches := re.FindStringSubmatch(string(body))13 fmt.Println(matches[1])14}15import (16func main() {17 if err != nil {18 fmt.Println(err)19 }20 defer resp.Body.Close()21 body, err := ioutil.ReadAll(resp.Body)22 if err != nil {23 fmt.Println(err)24 }25 re := regexp.MustCompile("<title>(.*)</title>")26 matches := re.FindAllString(string(body), -1)27 fmt.Println(matches)28}29import (30func main() {31 if err != nil {32 fmt.Println(err)33 }34 defer resp.Body.Close()35 body, err := ioutil.ReadAll(resp.Body)36 if err != nil {37 fmt.Println(err)38 }39 re := regexp.MustCompile("<title>(.*)</title>")40 matches := re.FindAllStringSubmatch(string(body), -1)41 fmt.Println(matches)42}43import (44func main() {45 if err != nil {46 fmt.Println(err)47 }48 defer resp.Body.Close()49 body, err := ioutil.ReadAll(resp.Body)
Matches
Using AI Code Generation
1import (2func main() {3 resp, err := http.Get(url)4 if err != nil {5 fmt.Fprintf(os.Stderr, "fetch: %v6 os.Exit(1)7 }8 b, err := ioutil.ReadAll(resp.Body)9 resp.Body.Close()10 if err != nil {11 fmt.Fprintf(os.Stderr, "fetch: reading %s: %v12 os.Exit(1)13 }14 doc, err := html.Parse(resp.Body)15 if err != nil {16 fmt.Fprintf(os.Stderr, "findlinks1: %v17 os.Exit(1)18 }19 for _, link := range visit(nil, doc) {20 fmt.Println(link)21 }22}23func visit(links []string, n *html.Node) []string {24 if n.Type == html.ElementNode && n.Data == "a" {25 for _, a := range n.Attr {26 if a.Key == "href" {27 links = append(links, a.Val)28 }29 }30 }31 for c := n.FirstChild; c != nil; c = c.NextSibling {32 links = visit(links, c)33 }34}
Matches
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error in getting response")5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println("Error in reading response")10 }11 doc, err := html.Parse(resp.Body)12 if err != nil {13 fmt.Println("Error in parsing response")14 }15 fmt.Println(doc)16 fmt.Println(html.UnescapeString(string(body)))17 fmt.Println("Title:", html.Title(string(body)))18 fmt.Println("Text:", html.EscapeString(string(body)))19 fmt.Println("Match:", html.Match([]byte("a"), []byte("a")))20 fmt.Println("Match:", html.Match([]byte("a"), []byte("b")))21 fmt.Println("Match:", html.Match([]byte("a"), []byte("ab")))22 fmt.Println("Match:", html.Match([]byte("a"), []byte("ba")))23 fmt.Println("Match:", html.Match([]byte("a"), []byte("")))24 fmt.Println("Match:", html.Match([]byte("a"), []byte(" ")))25}
Matches
Using AI Code Generation
1import (2func main() {3 for _, url := range os.Args[1:] {4 doc, err := html.Parse(getPageContent(url))5 if err != nil {6 fmt.Fprintf(os.Stderr, "findlinks1: %v7 os.Exit(1)8 }9 for _, link := range visit(nil, doc) {10 fmt.Println(link)11 }12 }13}14func getPageContent(url string) *http.Response {15 resp, err := http.Get(url)16 if err != nil {17 fmt.Fprintf(os.Stderr, "findlinks1: %v18 os.Exit(1)19 }20}21func visit(links []string, n *html.Node) []string {22 if n.Type == html.ElementNode && n.Data == "a" {23 for _, a := range n.Attr {24 if a.Key == "href" {25 links = append(links, a.Val)26 }27 }28 }29 for c := n.FirstChild; c != nil; c = c.NextSibling {30 links = visit(links, c)31 }32}33import (34func main() {35 for _, url := range os.Args[1:] {36 doc, err := html.Parse(getPageContent(url))37 if err != nil {38 fmt.Fprintf(os.Stderr, "findlinks1: %v39 os.Exit(1)40 }41 for _, link := range visit(nil, doc) {42 fmt.Println(link)43 }44 }45}46func getPageContent(url string) *http.Response {47 resp, err := http.Get(url)48 if err != nil {49 fmt.Fprintf(os.Stderr, "findlinks1: %v50 os.Exit(1)51 }52}53func visit(links []string, n *html.Node) []string {54 if n.Type == html.ElementNode && n.Data == "a" {55 for _, a := range n.Attr {56 if matched, _ := regexp.MatchString("^http", a.Val); matched {57 links = append(links,
Matches
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 doc, err := html.Parse(resp.Body)8 if err != nil {9 log.Fatal(err)10 }11 for _, link := range visit(nil, doc) {12 fmt.Println(link)13 }14}15func visit(links []string, n *html.Node) []string {16 if n.Type == html.ElementNode && n.Data == "a" {17 for _, a := range n.Attr {18 if a.Key == "href" {19 links = append(links, a.Val)20 }21 }22 }23 for c := n.FirstChild; c != nil; c = c.NextSibling {24 links = visit(links, c)25 }26}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!