Best K6 code snippet using html.Target
commands.go
Source:commands.go
...26}27// every element in structs that starts with an underscore is not an attribute definition,28// but rather hold concrete information about the command; usually, they are the29// fields with actual values30type _HtmlTarget struct {31 htmlOpenTag string32 htmlCloseTag string33}34var commands = map[string]interface{}{35 // Document36 Document: struct {37 BaseCommand38 BlockCommand39 RecursiveCommand40 }{},41 // Strong42 Strong: struct {43 BaseCommand44 _HtmlTarget45 }{46 _HtmlTarget: _HtmlTarget{`<b{{.attrs}}>`, `</b>`},47 },48 // Italic49 Italic: struct {50 BaseCommand51 _HtmlTarget52 }{53 _HtmlTarget: _HtmlTarget{`<i{{.attrs}}>`, `</i>`},54 },55 // inline code56 // for now, attributes are not supported57 InlineCode: struct {58 BaseCommand59 _HtmlTarget60 }{61 _HtmlTarget: _HtmlTarget{`<code{{.attrs}}>`, `</code>`},62 },63 // inline math64 // for now, attributes are not supported65 InlineMath: struct {66 BaseCommand67 MathCommand68 _HtmlTarget69 }{70 _HtmlTarget: _HtmlTarget{71 htmlOpenTag: `<span{{.attrs}}>\(`,72 htmlCloseTag: `\)</span>`,73 }},74 // link75 Link: struct {76 BaseCommand77 _HtmlTarget78 to string `html:"href"`79 }{80 _HtmlTarget: _HtmlTarget{81 htmlOpenTag: `<a{{.attrs}}>`,82 htmlCloseTag: `</a>`,83 },84 },85 // reference86 Reference: struct {87 BaseCommand88 _HtmlTarget89 refNum int90 to string91 }{92 _HtmlTarget: _HtmlTarget{93 htmlOpenTag: `<span{{.attrs}}>`,94 htmlCloseTag: `<a href="#{{.to}}" class="refname">{{.refNum}}</a></span>`,95 },96 },97 // dereference98 Dereference: struct {99 BaseCommand100 _HtmlTarget101 refNum int102 }{103 _HtmlTarget: _HtmlTarget{104 htmlOpenTag: `<span{{.attrs}}><a class="refname" >{{.refNum}}</a>`,105 htmlCloseTag: "</span>",106 },107 },108 // paragraph109 Paragraph: struct {110 BaseCommand111 RecursiveCommand112 _HtmlTarget113 }{114 _HtmlTarget: _HtmlTarget{`<div{{.attrs}}>`, `</div>`},115 },116 // quote117 Quote: struct {118 BaseCommand119 RecursiveCommand120 _HtmlTarget121 cite string `html:"cite"`122 }{123 _HtmlTarget: _HtmlTarget{124 htmlOpenTag: "<blockquote{{.attrs}}>",125 htmlCloseTag: "</blockquote>",126 },127 },128 // math block129 Math: struct {130 BaseCommand131 MathCommand132 BlockCommand133 CaptionedCommand134 _HtmlTarget135 }{136 _HtmlTarget: _HtmlTarget{`<div{{.attrs}} class="math-block">$$`, f(`$$%s</div>`, mixins.MathNumber)},137 },138 // code block139 Code: struct {140 BaseCommand141 BlockCommand142 CaptionedCommand143 _HtmlTarget144 lang string145 }{146 _HtmlTarget: _HtmlTarget{147 htmlOpenTag: `<div{{.attrs}} class="captionable"><pre><code class="language-{{or .lang "plain"}}">`,148 htmlCloseTag: f(`</code></pre>%s</div>`, mixins.Caption),149 },150 },151 // figure152 Figure: struct {153 BaseCommand154 BlockCommand155 CaptionedCommand156 _HtmlTarget157 src string `html:"src"`158 width int `html:"width"`159 height int `html:"height"`160 align string `html:"data-align"`161 }{162 _HtmlTarget: _HtmlTarget{163 htmlOpenTag: f(`<figure class="captionable"><img{{.attrs}}/>%s<figure>`, mixins.Caption),164 },165 },166 // box167 Box: struct {168 BaseCommand169 RecursiveCommand170 _HtmlTarget171 title string172 }{173 _HtmlTarget: _HtmlTarget{174 htmlOpenTag: `<div{{.attrs}} class="box">{{if .title}}<div class="box-title">{{.title}}</div>{{end}}`,175 htmlCloseTag: "</div>",176 },177 },178 Title: struct {179 BaseCommand180 BlockCommand181 _HtmlTarget182 }{183 _HtmlTarget: _HtmlTarget{184 htmlOpenTag: `<h1{{.attrs}}><a class="section-num">{{.sectionNum}}</a>`,185 htmlCloseTag: "</h1>",186 },187 },188 Subtitle: struct {189 BaseCommand190 BlockCommand191 _HtmlTarget192 }{193 _HtmlTarget: _HtmlTarget{194 htmlOpenTag: `<h2{{.attrs}}><a class="section-num">{{.sectionNum}}</a>`,195 htmlCloseTag: "</h2>",196 },197 },198 Heading: struct {199 BaseCommand200 BlockCommand201 _HtmlTarget202 }{203 _HtmlTarget: _HtmlTarget{204 htmlOpenTag: `<h3{{.attrs}}><a class="section-num">{{.sectionNum}}</a>`,205 htmlCloseTag: "</h3>",206 },207 },208 OrderedList: struct {209 BaseCommand210 RecursiveCommand211 _HtmlTarget212 }{213 _HtmlTarget: _HtmlTarget{214 htmlOpenTag: "<ol{{.attrs}}>",215 htmlCloseTag: "</ol>",216 },217 },218 UnorderedList: struct {219 BaseCommand220 RecursiveCommand221 _HtmlTarget222 }{223 _HtmlTarget: _HtmlTarget{224 htmlOpenTag: "<ul{{.attrs}}>",225 htmlCloseTag: "</ul>",226 },227 },228 ListItem: struct {229 BaseCommand230 RecursiveCommand231 _HtmlTarget232 value int `html:"value"`233 numType string `html:"type"`234 }{235 _HtmlTarget: _HtmlTarget{236 htmlOpenTag: "<li{{.attrs}}>",237 htmlCloseTag: "</li>",238 },239 },240}241// singleton242var attrsTypes map[string]map[string]reflect.Type243// GetAttrTypes returns the lookup map of the attribute types of the command244func GetAttrTypes(command string) (map[string]reflect.Type, bool) {245 if attrsTypes == nil {246 attrsTypes = make(map[string]map[string]reflect.Type)247 for k, v := range commands {248 attrsTypes[k] = make(map[string]reflect.Type)249 deepExtractField(v, attrsTypes[k])250 }251 }252 if attrsTypes[command] == nil {253 return nil, false254 }255 return attrsTypes[command], true256}257// HasAttr returns if a command has an attribute258func HasAttr(command string, attr string) (ok bool) {259 attrs, ok := GetAttrTypes(command)260 if !ok {261 return false262 }263 _, ok = attrs[attr]264 return265}266func IsCommand(command string, baseCommand interface{}) bool {267 if def, ok := commands[command]; ok {268 return embedsBaseModel(def, baseCommand)269 }270 return false271}272func embedsBaseModel(v interface{}, baseType interface{}) bool {273 rt := reflect.TypeOf(v)274 if rt.Kind() != reflect.Struct {275 return false276 }277 for i := 0; i < rt.NumField(); i++ {278 if sf := rt.Field(i); sf.Type == reflect.TypeOf(baseType) && sf.Anonymous {279 return true280 } else if sub := reflect.ValueOf(v).Field(i); sf.IsExported() && sub.Kind() == reflect.Struct {281 if embedsBaseModel(sub.Interface(), baseType) {282 return true283 }284 }285 }286 return false287}288// IsBlock returns if a command is a block289func IsBlock(command string) bool {290 return command == Math || IsCommand(command, BlockCommand{})291}292// IsCaptioned returns if a command is a captioned293func IsCaptioned(command string) bool {294 return IsCommand(command, CaptionedCommand{})295}296func IsRecursive(command string) bool {297 return IsCommand(command, RecursiveCommand{})298}299func deepExtractField(value interface{}, res map[string]reflect.Type) []reflect.Value {300 fields := make([]reflect.Value, 0)301 ifv, ift := reflect.ValueOf(value), reflect.TypeOf(value)302 for i := 0; i < ift.NumField(); i++ {303 v := ifv.Field(i)304 switch v.Kind() {305 case reflect.Struct:306 if ift.Field(i).IsExported() {307 fields = append(fields, deepExtractField(v.Interface(), res)...)308 }309 default:310 res[ift.Field(i).Name] = v.Type()311 fields = append(fields, v)312 }313 }314 return fields315}316func GetHtmlAttrName(command, name string) (tag string, ok bool) {317 attrs, ok := commands[command]318 if !ok {319 return320 }321 return extractTagValue(attrs, "html", name)322}323// extractTagValue get the value of a tag324func extractTagValue(value interface{}, tag, key string) (htmlAttr string, ok bool) {325 ifv, ift := reflect.ValueOf(value), reflect.TypeOf(value)326 for i := 0; i < ift.NumField(); i++ {327 v := ifv.Field(i)328 if f := ift.Field(i); f.Name == key {329 res := f.Tag.Get(tag)330 if res != "" {331 return f.Tag.Get("html"), true332 }333 }334 if v.Kind() == reflect.Struct {335 if ift.Field(i).IsExported() {336 htmlAttr, ok = extractTagValue(v.Interface(), tag, key)337 if ok {338 return339 }340 }341 }342 }343 return "", false344}345// GetHtmlTags returns the open tag and the close tag based on the commands definitions346func GetHtmlTags(command string, vars map[string]interface{}) (string, string) {347 if attrs, ok := commands[command]; ok {348 htmlTarget := reflect.349 ValueOf(attrs).350 FieldByName(reflect.TypeOf(_HtmlTarget{}).Name())351 op, cl := htmlTarget.Field(0).String(), htmlTarget.Field(1).String()352 attrsBuilder := strings.Builder{}353 attrsBuilder.WriteString("")354 for k, v := range vars {355 htmlAttrName, ok := GetHtmlAttrName(command, k)356 if !ok {357 // just ignore the attribute because it is probably not defined358 // for the HTML target359 continue360 }361 attrsBuilder.WriteRune(' ')362 attrsBuilder.WriteString(htmlAttrName)363 attrsBuilder.WriteString("=\"")364 // for special cases, do not use the attribute building; use separate365 // template instead...
utilities.go
Source:utilities.go
1package goquery2import (3 "bytes"4 "golang.org/x/net/html"5)6// used to determine if a set (map[*html.Node]bool) should be used7// instead of iterating over a slice. The set uses more memory and8// is slower than slice iteration for small N.9const minNodesForSet = 100010var nodeNames = []string{11 html.ErrorNode: "#error",12 html.TextNode: "#text",13 html.DocumentNode: "#document",14 html.CommentNode: "#comment",15}16// NodeName returns the node name of the first element in the selection.17// It tries to behave in a similar way as the DOM's nodeName property18// (https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName).19//20// Go's net/html package defines the following node types, listed with21// the corresponding returned value from this function:22//23// ErrorNode : #error24// TextNode : #text25// DocumentNode : #document26// ElementNode : the element's tag name27// CommentNode : #comment28// DoctypeNode : the name of the document type29//30func NodeName(s *Selection) string {31 if s.Length() == 0 {32 return ""33 }34 switch n := s.Get(0); n.Type {35 case html.ElementNode, html.DoctypeNode:36 return n.Data37 default:38 if n.Type >= 0 && int(n.Type) < len(nodeNames) {39 return nodeNames[n.Type]40 }41 return ""42 }43}44// OuterHtml returns the outer HTML rendering of the first item in45// the selection - that is, the HTML including the first element's46// tag and attributes.47//48// Unlike InnerHtml, this is a function and not a method on the Selection,49// because this is not a jQuery method (in javascript-land, this is50// a property provided by the DOM).51func OuterHtml(s *Selection) (string, error) {52 var buf bytes.Buffer53 if s.Length() == 0 {54 return "", nil55 }56 n := s.Get(0)57 if err := html.Render(&buf, n); err != nil {58 return "", err59 }60 return buf.String(), nil61}62// Loop through all container nodes to search for the target node.63func sliceContains(container []*html.Node, contained *html.Node) bool {64 for _, n := range container {65 if nodeContains(n, contained) {66 return true67 }68 }69 return false70}71// Checks if the contained node is within the container node.72func nodeContains(container *html.Node, contained *html.Node) bool {73 // Check if the parent of the contained node is the container node, traversing74 // upward until the top is reached, or the container is found.75 for contained = contained.Parent; contained != nil; contained = contained.Parent {76 if container == contained {77 return true78 }79 }80 return false81}82// Checks if the target node is in the slice of nodes.83func isInSlice(slice []*html.Node, node *html.Node) bool {84 return indexInSlice(slice, node) > -185}86// Returns the index of the target node in the slice, or -1.87func indexInSlice(slice []*html.Node, node *html.Node) int {88 if node != nil {89 for i, n := range slice {90 if n == node {91 return i92 }93 }94 }95 return -196}97// Appends the new nodes to the target slice, making sure no duplicate is added.98// There is no check to the original state of the target slice, so it may still99// contain duplicates. The target slice is returned because append() may create100// a new underlying array. If targetSet is nil, a local set is created with the101// target if len(target) + len(nodes) is greater than minNodesForSet.102func appendWithoutDuplicates(target []*html.Node, nodes []*html.Node, targetSet map[*html.Node]bool) []*html.Node {103 // if there are not that many nodes, don't use the map, faster to just use nested loops104 // (unless a non-nil targetSet is passed, in which case the caller knows better).105 if targetSet == nil && len(target)+len(nodes) < minNodesForSet {106 for _, n := range nodes {107 if !isInSlice(target, n) {108 target = append(target, n)109 }110 }111 return target112 }113 // if a targetSet is passed, then assume it is reliable, otherwise create one114 // and initialize it with the current target contents.115 if targetSet == nil {116 targetSet = make(map[*html.Node]bool, len(target))117 for _, n := range target {118 targetSet[n] = true119 }120 }121 for _, n := range nodes {122 if !targetSet[n] {123 target = append(target, n)124 targetSet[n] = true125 }126 }127 return target128}129// Loop through a selection, returning only those nodes that pass the predicate130// function.131func grep(sel *Selection, predicate func(i int, s *Selection) bool) (result []*html.Node) {132 for i, n := range sel.Nodes {133 if predicate(i, newSingleSelection(n, sel.document)) {134 result = append(result, n)135 }136 }137 return result138}139// Creates a new Selection object based on the specified nodes, and keeps the140// source Selection object on the stack (linked list).141func pushStack(fromSel *Selection, nodes []*html.Node) *Selection {142 result := &Selection{nodes, fromSel.document, fromSel}143 return result144}...
Target
Using AI Code Generation
1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer res.Body.Close()7 if res.StatusCode != 200 {8 panic(res.Status)9 }10 doc, err := goquery.NewDocumentFromReader(res.Body)11 if err != nil {12 panic(err)13 }14 doc.Find("a").Each(func(i int, s *goquery.Selection) {15 band := s.Text()16 title := s.Find("a").Text()17 fmt.Printf("Review %d: %s - %s18 })19}
Target
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer res.Body.Close()7 if res.StatusCode != 200 {8 log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)9 }10 doc, err := goquery.NewDocumentFromReader(res.Body)11 if err != nil {12 log.Fatal(err)13 }14 doc.Find(".gb_g").Each(func(i int, s *goquery.Selection) {15 band := s.Find("a").Text()16 title := s.Find("a").Text()17 fmt.Printf("Review %d: %s - %s18 })19}
Target
Using AI Code Generation
1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer res.Body.Close()7 if res.StatusCode != 200 {8 panic(res.Status)9 }10 doc, err := goquery.NewDocumentFromReader(res.Body)11 if err != nil {12 panic(err)13 }14 doc.Find(".gb_P").Each(func(i int, s *goquery.Selection) {15 band := s.Find("a").Text()16 title := s.Find("span").Text()17 fmt.Printf("Review %d: %s - %s18 })19}
Target
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}
Target
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find("a").Each(func(i int, s *goquery.Selection) {7 link, _ := s.Attr("href")8 fmt.Printf("Link: %s9 })10}
Target
Using AI Code Generation
1func main() {2 if err != nil {3 log.Fatal(err)4 }5 n := links.FirstAnchor(doc)6 if n == nil {7 log.Fatal("no link found")8 }9 fmt.Println(links.Target(n))10}11func Target(n *html.Node) string12func main() {13 if err != nil {14 log.Fatal(err)15 }16 n := links.FirstAnchor(doc)17 if n == nil {18 log.Fatal("no link found")19 }20 fmt.Println(links.Target(n))21}
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!!