Best K6 code snippet using html.Type
selector.go
Source:selector.go
...144 tag string145}146// Matches elements with a given tag name.147func (t tagSelector) Match(n *html.Node) bool {148 return n.Type == html.ElementNode && n.Data == t.tag149}150func (c tagSelector) Specificity() Specificity {151 return Specificity{0, 0, 1}152}153type classSelector struct {154 class string155}156// Matches elements by class attribute.157func (t classSelector) Match(n *html.Node) bool {158 return matchAttribute(n, "class", func(s string) bool {159 return matchInclude(t.class, s)160 })161}162func (c classSelector) Specificity() Specificity {163 return Specificity{0, 1, 0}164}165type idSelector struct {166 id string167}168// Matches elements by id attribute.169func (t idSelector) Match(n *html.Node) bool {170 return matchAttribute(n, "id", func(s string) bool {171 return s == t.id172 })173}174func (c idSelector) Specificity() Specificity {175 return Specificity{1, 0, 0}176}177type attrSelector struct {178 key, val, operation string179 regexp *regexp.Regexp180}181// Matches elements by attribute value.182func (t attrSelector) Match(n *html.Node) bool {183 switch t.operation {184 case "":185 return matchAttribute(n, t.key, func(string) bool { return true })186 case "=":187 return matchAttribute(n, t.key, func(s string) bool { return s == t.val })188 case "!=":189 return attributeNotEqualMatch(t.key, t.val, n)190 case "~=":191 // matches elements where the attribute named key is a whitespace-separated list that includes val.192 return matchAttribute(n, t.key, func(s string) bool { return matchInclude(t.val, s) })193 case "|=":194 return attributeDashMatch(t.key, t.val, n)195 case "^=":196 return attributePrefixMatch(t.key, t.val, n)197 case "$=":198 return attributeSuffixMatch(t.key, t.val, n)199 case "*=":200 return attributeSubstringMatch(t.key, t.val, n)201 case "#=":202 return attributeRegexMatch(t.key, t.regexp, n)203 default:204 panic(fmt.Sprintf("unsuported operation : %s", t.operation))205 }206}207// matches elements where the attribute named key satisifes the function f.208func matchAttribute(n *html.Node, key string, f func(string) bool) bool {209 if n.Type != html.ElementNode {210 return false211 }212 for _, a := range n.Attr {213 if a.Key == key && f(a.Val) {214 return true215 }216 }217 return false218}219// attributeNotEqualMatch matches elements where220// the attribute named key does not have the value val.221func attributeNotEqualMatch(key, val string, n *html.Node) bool {222 if n.Type != html.ElementNode {223 return false224 }225 for _, a := range n.Attr {226 if a.Key == key && a.Val == val {227 return false228 }229 }230 return true231}232// returns true if s is a whitespace-separated list that includes val.233func matchInclude(val, s string) bool {234 for s != "" {235 i := strings.IndexAny(s, " \t\r\n\f")236 if i == -1 {237 return s == val238 }239 if s[:i] == val {240 return true241 }242 s = s[i+1:]243 }244 return false245}246// matches elements where the attribute named key equals val or starts with val plus a hyphen.247func attributeDashMatch(key, val string, n *html.Node) bool {248 return matchAttribute(n, key,249 func(s string) bool {250 if s == val {251 return true252 }253 if len(s) <= len(val) {254 return false255 }256 if s[:len(val)] == val && s[len(val)] == '-' {257 return true258 }259 return false260 })261}262// attributePrefixMatch returns a Selector that matches elements where263// the attribute named key starts with val.264func attributePrefixMatch(key, val string, n *html.Node) bool {265 return matchAttribute(n, key,266 func(s string) bool {267 if strings.TrimSpace(s) == "" {268 return false269 }270 return strings.HasPrefix(s, val)271 })272}273// attributeSuffixMatch matches elements where274// the attribute named key ends with val.275func attributeSuffixMatch(key, val string, n *html.Node) bool {276 return matchAttribute(n, key,277 func(s string) bool {278 if strings.TrimSpace(s) == "" {279 return false280 }281 return strings.HasSuffix(s, val)282 })283}284// attributeSubstringMatch matches nodes where285// the attribute named key contains val.286func attributeSubstringMatch(key, val string, n *html.Node) bool {287 return matchAttribute(n, key,288 func(s string) bool {289 if strings.TrimSpace(s) == "" {290 return false291 }292 return strings.Contains(s, val)293 })294}295// attributeRegexMatch matches nodes where296// the attribute named key matches the regular expression rx297func attributeRegexMatch(key string, rx *regexp.Regexp, n *html.Node) bool {298 return matchAttribute(n, key,299 func(s string) bool {300 return rx.MatchString(s)301 })302}303func (c attrSelector) Specificity() Specificity {304 return Specificity{0, 1, 0}305}306// ---------------- Pseudo class selectors ----------------307// we use severals concrete types of pseudo-class selectors308type relativePseudoClassSelector struct {309 name string // one of "not", "has", "haschild"310 match SelectorGroup311}312func (s relativePseudoClassSelector) Match(n *html.Node) bool {313 if n.Type != html.ElementNode {314 return false315 }316 switch s.name {317 case "not":318 // matches elements that do not match a.319 return !s.match.Match(n)320 case "has":321 // matches elements with any descendant that matches a.322 return hasDescendantMatch(n, s.match)323 case "haschild":324 // matches elements with a child that matches a.325 return hasChildMatch(n, s.match)326 default:327 panic(fmt.Sprintf("unsupported relative pseudo class selector : %s", s.name))328 }329}330// hasChildMatch returns whether n has any child that matches a.331func hasChildMatch(n *html.Node, a Matcher) bool {332 for c := n.FirstChild; c != nil; c = c.NextSibling {333 if a.Match(c) {334 return true335 }336 }337 return false338}339// hasDescendantMatch performs a depth-first search of n's descendants,340// testing whether any of them match a. It returns true as soon as a match is341// found, or false if no match is found.342func hasDescendantMatch(n *html.Node, a Matcher) bool {343 for c := n.FirstChild; c != nil; c = c.NextSibling {344 if a.Match(c) || (c.Type == html.ElementNode && hasDescendantMatch(c, a)) {345 return true346 }347 }348 return false349}350// Specificity returns the specificity of the most specific selectors351// in the pseudo-class arguments.352// See https://www.w3.org/TR/selectors/#specificity-rules353func (s relativePseudoClassSelector) Specificity() Specificity {354 var max Specificity355 for _, sel := range s.match {356 newSpe := sel.Specificity()357 if max.Less(newSpe) {358 max = newSpe359 }360 }361 return max362}363type containsPseudoClassSelector struct {364 own bool365 value string366}367func (s containsPseudoClassSelector) Match(n *html.Node) bool {368 var text string369 if s.own {370 // matches nodes that directly contain the given text371 text = strings.ToLower(nodeOwnText(n))372 } else {373 // matches nodes that contain the given text.374 text = strings.ToLower(nodeText(n))375 }376 return strings.Contains(text, s.value)377}378func (s containsPseudoClassSelector) Specificity() Specificity {379 return Specificity{0, 1, 0}380}381type regexpPseudoClassSelector struct {382 own bool383 regexp *regexp.Regexp384}385func (s regexpPseudoClassSelector) Match(n *html.Node) bool {386 var text string387 if s.own {388 // matches nodes whose text directly matches the specified regular expression389 text = nodeOwnText(n)390 } else {391 // matches nodes whose text matches the specified regular expression392 text = nodeText(n)393 }394 return s.regexp.MatchString(text)395}396// writeNodeText writes the text contained in n and its descendants to b.397func writeNodeText(n *html.Node, b *bytes.Buffer) {398 switch n.Type {399 case html.TextNode:400 b.WriteString(n.Data)401 case html.ElementNode:402 for c := n.FirstChild; c != nil; c = c.NextSibling {403 writeNodeText(c, b)404 }405 }406}407// nodeText returns the text contained in n and its descendants.408func nodeText(n *html.Node) string {409 var b bytes.Buffer410 writeNodeText(n, &b)411 return b.String()412}413// nodeOwnText returns the contents of the text nodes that are direct414// children of n.415func nodeOwnText(n *html.Node) string {416 var b bytes.Buffer417 for c := n.FirstChild; c != nil; c = c.NextSibling {418 if c.Type == html.TextNode {419 b.WriteString(c.Data)420 }421 }422 return b.String()423}424func (s regexpPseudoClassSelector) Specificity() Specificity {425 return Specificity{0, 1, 0}426}427type nthPseudoClassSelector struct {428 a, b int429 last, ofType bool430}431func (s nthPseudoClassSelector) Match(n *html.Node) bool {432 if s.a == 0 {433 if s.last {434 return simpleNthLastChildMatch(s.b, s.ofType, n)435 } else {436 return simpleNthChildMatch(s.b, s.ofType, n)437 }438 }439 return nthChildMatch(s.a, s.b, s.last, s.ofType, n)440}441// nthChildMatch implements :nth-child(an+b).442// If last is true, implements :nth-last-child instead.443// If ofType is true, implements :nth-of-type instead.444func nthChildMatch(a, b int, last, ofType bool, n *html.Node) bool {445 if n.Type != html.ElementNode {446 return false447 }448 parent := n.Parent449 if parent == nil {450 return false451 }452 if parent.Type == html.DocumentNode {453 return false454 }455 i := -1456 count := 0457 for c := parent.FirstChild; c != nil; c = c.NextSibling {458 if (c.Type != html.ElementNode) || (ofType && c.Data != n.Data) {459 continue460 }461 count++462 if c == n {463 i = count464 if !last {465 break466 }467 }468 }469 if i == -1 {470 // This shouldn't happen, since n should always be one of its parent's children.471 return false472 }473 if last {474 i = count - i + 1475 }476 i -= b477 if a == 0 {478 return i == 0479 }480 return i%a == 0 && i/a >= 0481}482// simpleNthChildMatch implements :nth-child(b).483// If ofType is true, implements :nth-of-type instead.484func simpleNthChildMatch(b int, ofType bool, n *html.Node) bool {485 if n.Type != html.ElementNode {486 return false487 }488 parent := n.Parent489 if parent == nil {490 return false491 }492 if parent.Type == html.DocumentNode {493 return false494 }495 count := 0496 for c := parent.FirstChild; c != nil; c = c.NextSibling {497 if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {498 continue499 }500 count++501 if c == n {502 return count == b503 }504 if count >= b {505 return false506 }507 }508 return false509}510// simpleNthLastChildMatch implements :nth-last-child(b).511// If ofType is true, implements :nth-last-of-type instead.512func simpleNthLastChildMatch(b int, ofType bool, n *html.Node) bool {513 if n.Type != html.ElementNode {514 return false515 }516 parent := n.Parent517 if parent == nil {518 return false519 }520 if parent.Type == html.DocumentNode {521 return false522 }523 count := 0524 for c := parent.LastChild; c != nil; c = c.PrevSibling {525 if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {526 continue527 }528 count++529 if c == n {530 return count == b531 }532 if count >= b {533 return false534 }535 }536 return false537}538// Specificity for nth-child pseudo-class.539// Does not support a list of selectors540func (s nthPseudoClassSelector) Specificity() Specificity {541 return Specificity{0, 1, 0}542}543type onlyChildPseudoClassSelector struct {544 ofType bool545}546// Match implements :only-child.547// If `ofType` is true, it implements :only-of-type instead.548func (s onlyChildPseudoClassSelector) Match(n *html.Node) bool {549 if n.Type != html.ElementNode {550 return false551 }552 parent := n.Parent553 if parent == nil {554 return false555 }556 if parent.Type == html.DocumentNode {557 return false558 }559 count := 0560 for c := parent.FirstChild; c != nil; c = c.NextSibling {561 if (c.Type != html.ElementNode) || (s.ofType && c.Data != n.Data) {562 continue563 }564 count++565 if count > 1 {566 return false567 }568 }569 return count == 1570}571func (s onlyChildPseudoClassSelector) Specificity() Specificity {572 return Specificity{0, 1, 0}573}574type inputPseudoClassSelector struct{}575// Matches input, select, textarea and button elements.576func (s inputPseudoClassSelector) Match(n *html.Node) bool {577 return n.Type == html.ElementNode && (n.Data == "input" || n.Data == "select" || n.Data == "textarea" || n.Data == "button")578}579func (s inputPseudoClassSelector) Specificity() Specificity {580 return Specificity{0, 1, 0}581}582type emptyElementPseudoClassSelector struct{}583// Matches empty elements.584func (s emptyElementPseudoClassSelector) Match(n *html.Node) bool {585 if n.Type != html.ElementNode {586 return false587 }588 for c := n.FirstChild; c != nil; c = c.NextSibling {589 switch c.Type {590 case html.ElementNode, html.TextNode:591 return false592 }593 }594 return true595}596func (s emptyElementPseudoClassSelector) Specificity() Specificity {597 return Specificity{0, 1, 0}598}599type rootPseudoClassSelector struct{}600// Match implements :root601func (s rootPseudoClassSelector) Match(n *html.Node) bool {602 if n.Type != html.ElementNode {603 return false604 }605 if n.Parent == nil {606 return false607 }608 return n.Parent.Type == html.DocumentNode609}610func (s rootPseudoClassSelector) Specificity() Specificity {611 return Specificity{0, 1, 0}612}613type compoundSelector struct {614 selectors []Sel615}616// Matches elements if each sub-selectors matches.617func (t compoundSelector) Match(n *html.Node) bool {618 if len(t.selectors) == 0 {619 return n.Type == html.ElementNode620 }621 for _, sel := range t.selectors {622 if !sel.Match(n) {623 return false624 }625 }626 return true627}628func (s compoundSelector) Specificity() Specificity {629 var out Specificity630 for _, sel := range s.selectors {631 out = out.Add(sel.Specificity())632 }633 return out634}635type combinedSelector struct {636 first Sel637 combinator byte638 second Sel639}640func (t combinedSelector) Match(n *html.Node) bool {641 if t.first == nil {642 return false // maybe we should panic643 }644 switch t.combinator {645 case 0:646 return t.first.Match(n)647 case ' ':648 return descendantMatch(t.first, t.second, n)649 case '>':650 return childMatch(t.first, t.second, n)651 case '+':652 return siblingMatch(t.first, t.second, true, n)653 case '~':654 return siblingMatch(t.first, t.second, false, n)655 default:656 panic("unknown combinator")657 }658}659// matches an element if it matches d and has an ancestor that matches a.660func descendantMatch(a, d Matcher, n *html.Node) bool {661 if !d.Match(n) {662 return false663 }664 for p := n.Parent; p != nil; p = p.Parent {665 if a.Match(p) {666 return true667 }668 }669 return false670}671// matches an element if it matches d and its parent matches a.672func childMatch(a, d Matcher, n *html.Node) bool {673 return d.Match(n) && n.Parent != nil && a.Match(n.Parent)674}675// matches an element if it matches s2 and is preceded by an element that matches s1.676// If adjacent is true, the sibling must be immediately before the element.677func siblingMatch(s1, s2 Matcher, adjacent bool, n *html.Node) bool {678 if !s2.Match(n) {679 return false680 }681 if adjacent {682 for n = n.PrevSibling; n != nil; n = n.PrevSibling {683 if n.Type == html.TextNode || n.Type == html.CommentNode {684 continue685 }686 return s1.Match(n)687 }688 return false689 }690 // Walk backwards looking for element that matches s1691 for c := n.PrevSibling; c != nil; c = c.PrevSibling {692 if s1.Match(c) {693 return true694 }695 }696 return false697}...
mediatype_test.go
Source:mediatype_test.go
...80 expectedRest, rest, param, value, test[0])81 }82 }83}84type mediaTypeTest struct {85 in string86 t string87 p map[string]string88}89func TestParseMediaType(t *testing.T) {90 // Convenience map initializer91 m := func(s ...string) map[string]string {92 sm := make(map[string]string)93 for i := 0; i < len(s); i += 2 {94 sm[s[i]] = s[i+1]95 }96 return sm97 }98 nameFoo := map[string]string{"name": "foo"}99 tests := []mediaTypeTest{100 {`form-data; name="foo"`, "form-data", nameFoo},101 {` form-data ; name=foo`, "form-data", nameFoo},102 {`FORM-DATA;name="foo"`, "form-data", nameFoo},103 {` FORM-DATA ; name="foo"`, "form-data", nameFoo},104 {` FORM-DATA ; name="foo"`, "form-data", nameFoo},105 {`form-data; key=value; blah="value";name="foo" `,106 "form-data",107 m("key", "value", "blah", "value", "name", "foo")},108 {`foo; key=val1; key=the-key-appears-again-which-is-bogus`,109 "", m()},110 // From RFC 2231:111 {`application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A`,112 "application/x-stuff",113 m("title", "This is ***fun***")},114 {`message/external-body; access-type=URL; ` +115 `URL*0="ftp://";` +116 `URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"`,117 "message/external-body",118 m("access-type", "URL",119 "url", "ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar")},120 {`application/x-stuff; ` +121 `title*0*=us-ascii'en'This%20is%20even%20more%20; ` +122 `title*1*=%2A%2A%2Afun%2A%2A%2A%20; ` +123 `title*2="isn't it!"`,124 "application/x-stuff",125 m("title", "This is even more ***fun*** isn't it!")},126 // Tests from http://greenbytes.de/tech/tc2231/127 // TODO(bradfitz): add the rest of the tests from that site.128 {`attachment; filename="f\oo.html"`,129 "attachment",130 m("filename", "foo.html")},131 {`attachment; filename="\"quoting\" tested.html"`,132 "attachment",133 m("filename", `"quoting" tested.html`)},134 {`attachment; filename="Here's a semicolon;.html"`,135 "attachment",136 m("filename", "Here's a semicolon;.html")},137 {`attachment; foo="\"\\";filename="foo.html"`,138 "attachment",139 m("foo", "\"\\", "filename", "foo.html")},140 {`attachment; filename=foo.html`,141 "attachment",142 m("filename", "foo.html")},143 {`attachment; filename=foo.html ;`,144 "attachment",145 m("filename", "foo.html")},146 {`attachment; filename='foo.html'`,147 "attachment",148 m("filename", "'foo.html'")},149 {`attachment; filename="foo-%41.html"`,150 "attachment",151 m("filename", "foo-%41.html")},152 {`attachment; filename="foo-%\41.html"`,153 "attachment",154 m("filename", "foo-%41.html")},155 {`filename=foo.html`,156 "", m()},157 {`x=y; filename=foo.html`,158 "", m()},159 {`"foo; filename=bar;baz"; filename=qux`,160 "", m()},161 {`inline; attachment; filename=foo.html`,162 "", m()},163 {`attachment; filename="foo.html".txt`,164 "", m()},165 {`attachment; filename="bar`,166 "", m()},167 {`attachment; creation-date="Wed, 12 Feb 1997 16:29:51 -0500"`,168 "attachment",169 m("creation-date", "Wed, 12 Feb 1997 16:29:51 -0500")},170 {`foobar`, "foobar", m()},171 {`attachment; filename* =UTF-8''foo-%c3%a4.html`,172 "attachment",173 m("filename", "foo-ä.html")},174 {`attachment; filename*=UTF-8''A-%2541.html`,175 "attachment",176 m("filename", "A-%41.html")},177 {`attachment; filename*0="foo."; filename*1="html"`,178 "attachment",179 m("filename", "foo.html")},180 {`attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=".html"`,181 "attachment",182 m("filename", "foo-ä.html")},183 {`attachment; filename*0="foo"; filename*01="bar"`,184 "attachment",185 m("filename", "foo")},186 {`attachment; filename*0="foo"; filename*2="bar"`,187 "attachment",188 m("filename", "foo")},189 {`attachment; filename*1="foo"; filename*2="bar"`,190 "attachment", m()},191 {`attachment; filename*1="bar"; filename*0="foo"`,192 "attachment",193 m("filename", "foobar")},194 {`attachment; filename="foo-ae.html"; filename*=UTF-8''foo-%c3%a4.html`,195 "attachment",196 m("filename", "foo-ä.html")},197 {`attachment; filename*=UTF-8''foo-%c3%a4.html; filename="foo-ae.html"`,198 "attachment",199 m("filename", "foo-ä.html")},200 // Browsers also just send UTF-8 directly without RFC 2231,201 // at least when the source page is served with UTF-8.202 {`form-data; firstname="ÐÑÑд"; lastname="ФиÑпаÑÑик"`,203 "form-data",204 m("firstname", "ÐÑÑд", "lastname", "ФиÑпаÑÑик")},205 // Empty string used to be mishandled.206 {`foo; bar=""`, "foo", m("bar", "")},207 }208 for _, test := range tests {209 mt, params, err := ParseMediaType(test.in)210 if err != nil {211 if test.t != "" {212 t.Errorf("for input %q, unexpected error: %v", test.in, err)213 continue214 }215 continue216 }217 if g, e := mt, test.t; g != e {218 t.Errorf("for input %q, expected type %q, got %q",219 test.in, e, g)220 continue221 }222 if len(params) == 0 && len(test.p) == 0 {223 continue224 }225 if !reflect.DeepEqual(params, test.p) {226 t.Errorf("for input %q, wrong params.\n"+227 "expected: %#v\n"+228 " got: %#v",229 test.in, test.p, params)230 }231 }232}233type badMediaTypeTest struct {234 in string235 err string236}237var badMediaTypeTests = []badMediaTypeTest{238 {"bogus ;=========", "mime: invalid media parameter"},239 {"bogus/<script>alert</script>", "mime: expected token after slash"},240 {"bogus/bogus<script>alert</script>", "mime: unexpected content after media subtype"},241}242func TestParseMediaTypeBogus(t *testing.T) {243 for _, tt := range badMediaTypeTests {244 mt, params, err := ParseMediaType(tt.in)245 if err == nil {246 t.Errorf("ParseMediaType(%q) = nil error; want parse error", tt.in)247 continue248 }249 if err.Error() != tt.err {250 t.Errorf("ParseMediaType(%q) = err %q; want %q", tt.in, err.Error(), tt.err)251 }252 if params != nil {253 t.Errorf("ParseMediaType(%q): got non-nil params on error", tt.in)254 }255 if mt != "" {256 t.Errorf("ParseMediaType(%q): got non-empty media type string on error", tt.in)257 }258 }259}260type formatTest struct {261 typ string262 params map[string]string263 want string264}265var formatTests = []formatTest{266 {"noslash", map[string]string{"X": "Y"}, "noslash; x=Y"}, // e.g. Content-Disposition values (RFC 2183); issue 11289267 {"foo bar/baz", nil, ""},268 {"foo/bar baz", nil, ""},269 {"foo/BAR", nil, "foo/bar"},270 {"foo/BAR", map[string]string{"X": "Y"}, "foo/bar; x=Y"},271 {"foo/BAR", map[string]string{"space": "With space"}, `foo/bar; space="With space"`},272 {"foo/BAR", map[string]string{"quote": `With "quote`}, `foo/bar; quote="With \"quote"`},273 {"foo/BAR", map[string]string{"bslash": `With \backslash`}, `foo/bar; bslash="With \\backslash"`},274 {"foo/BAR", map[string]string{"both": `With \backslash and "quote`}, `foo/bar; both="With \\backslash and \"quote"`},275 {"foo/BAR", map[string]string{"": "empty attribute"}, ""},276 {"foo/BAR", map[string]string{"bad attribute": "baz"}, ""},277 {"foo/BAR", map[string]string{"nonascii": "not an ascii character: ä"}, ""},278 {"foo/bar", map[string]string{"a": "av", "b": "bv", "c": "cv"}, "foo/bar; a=av; b=bv; c=cv"},279 {"foo/bar", map[string]string{"0": "'", "9": "'"}, "foo/bar; 0='; 9='"},280 {"foo", map[string]string{"bar": ""}, `foo; bar=""`},281}282func TestFormatMediaType(t *testing.T) {283 for i, tt := range formatTests {284 got := FormatMediaType(tt.typ, tt.params)285 if got != tt.want {286 t.Errorf("%d. FormatMediaType(%q, %v) = %q; want %q", i, tt.typ, tt.params, got, tt.want)287 }288 }289}...
Type
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)6 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: %v\n", err)29 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 {37 if n.Data == "a" {38 for _, a := range n.Attr {39 if a.Key == "href" {40 links = append(links, a.Val)41 }42 }43 }44 if n.Data == "img" {45 for _, a := range n.Attr {46 if a.Key == "src" {47 links = append(links, a.Val)48 }49 }50 }51 }52 for c := n.FirstChild; c != nil; c = c.NextSibling {53 links = visit(links, c)54 }55}56import (57func main() {58 doc, err := html.Parse(os.Stdin)59 if err != nil {
Type
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)6 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 {14 links = append(links, n.Data)15 }16 for c := n.FirstChild; c != nil; c = c.NextSibling {17 links = visit(links, c)18 }19}
Type
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 os.Exit(1)6 }7 defer resp.Body.Close()8 bs := make([]byte, 99999)9 resp.Body.Read(bs)10 fmt.Println(string(bs))11}12import (13func main() {14 if err != nil {15 fmt.Println(err)16 os.Exit(1)17 }18 defer resp.Body.Close()19 bs := make([]byte, 99999)20 resp.Body.Read(bs)21 fmt.Println(string(bs))22}23import (24func main() {25 if err != nil {26 fmt.Println(err)27 os.Exit(1)28 }29 defer resp.Body.Close()30 bs := make([]byte, 99999)31 resp.Body.Read(bs)32 fmt.Println(string(bs))33}34import (35func main() {36 if err != nil {37 fmt.Println(err)38 os.Exit(1)39 }40 defer resp.Body.Close()41 bs := make([]byte, 99999)42 resp.Body.Read(bs)43 fmt.Println(string(bs))44}
Type
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(strings.NewReader("<html><head><title>My Page</title></head><body><h1>Hello World</h1></body></html>"))4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println(doc.Type)8}
Type
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("error")5 }6 defer resp.Body.Close()7 bs, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println("error")10 }11 fmt.Println(string(bs))12}13import (14func main() {15 if err != nil {16 fmt.Println("error")17 }18 defer resp.Body.Close()19 bs, err := ioutil.ReadAll(resp.Body)20 if err != nil {21 fmt.Println("error")22 }23 str := string(bs)24 fmt.Println(str)25}26import (27func main() {28 if err != nil {29 fmt.Println("error")30 }31 defer resp.Body.Close()32 bs, err := ioutil.ReadAll(resp.Body)33 if err != nil {34 fmt.Println("error")35 }36 str := string(bs)37 fmt.Println(str)38}39import (40func main() {41 if err != nil {42 fmt.Println("error")43 }44 defer resp.Body.Close()45 bs, err := ioutil.ReadAll(resp.Body)46 if err != nil {47 fmt.Println("error")48 }49 str := string(bs)50 fmt.Println(str)51}52import (53func main() {54 if err != nil {55 fmt.Println("error")56 }57 defer resp.Body.Close()58 bs, err := ioutil.ReadAll(resp.Body)59 if err != nil {60 fmt.Println("error")61 }62 str := string(bs)63 fmt.Println(str)64}
Type
Using AI Code Generation
1import (2func main() {3 fmt.Println(res)4 fmt.Println(res.Header)5 fmt.Println(res.Header["Date"])6 fmt.Println(res.Header.Get("Date"))7}8import (9func main() {10 fmt.Println(res)11 fmt.Println(res.Header)12 fmt.Println(res.Header["Date"])13 fmt.Println(res.Header.Get("Date"))14}15import (16func main() {17 fmt.Println(res)18 fmt.Println(res.Header)19 fmt.Println(res.Header["Date"])20 fmt.Println(res.Header.Get("Date"))21}22import (23func main() {24 fmt.Println(res)25 fmt.Println(res.Header)26 fmt.Println(res.Header["Date"])27 fmt.Println(res.Header.Get("Date"))28}29import (30func main() {31 fmt.Println(res)32 fmt.Println(res.Header)33 fmt.Println(res.Header["Date"])34 fmt.Println(res.Header.Get("Date"))35}36import (37func main() {38 fmt.Println(res)39 fmt.Println(res.Header)40 fmt.Println(res.Header["Date"])41 fmt.Println(res.Header.Get("Date"))42}43import (44func main() {45 fmt.Println(res)46 fmt.Println(res.Header)47 fmt.Println(res.Header["Date"])48 fmt.Println(res.Header.Get("Date"))49}
Type
Using AI Code Generation
1import (2func main() {3 doc, err = html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)6 os.Exit(1)7 }8 forEachNode(doc, startElement, endElement)9}10func forEachNode(n *html.Node, pre, post func(n *html.Node)) {11 if pre != nil {12 pre(n)13 }14 if n.FirstChild != nil {15 forEachNode(n.FirstChild, pre, post)16 }17 if post != nil {18 post(n)19 }20 if n.NextSibling != nil {21 forEachNode(n.NextSibling, pre, post)22 }23}24func startElement(n *html.Node) {25 if n.Type == html.ElementNode {26 fmt.Printf("%*s<%s>\n", n.Depth*2, "", n.Data)27 }28}29func endElement(n *html.Node) {30 if n.Type == html.ElementNode {31 fmt.Printf("%*s</%s>\n", n.Depth*2, "", n.Data)32 }33}34import (35func main() {36 doc, err = html.Parse(os.Stdin)37 if err != nil {38 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)39 os.Exit(1)40 }41 forEachNode(doc, startElement, endElement)42}43func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
Type
Using AI Code Generation
1import (2func main() {3 f, _ := os.Open("1.html")4 doc, _ := html.Parse(f)5 forEachNode(doc, startElement, endElement)6}7func forEachNode(n *html.Node, pre, post func(n *html.Node)) {8 if pre != nil {9 pre(n)10 }11 for c := n.FirstChild; c != nil; c = c.NextSibling {12 forEachNode(c, pre, post)13 }14 if post != nil {15 post(n)16 }17}18func startElement(n *html.Node) {19 if n.Type == html.ElementNode {20 fmt.Printf("<%s", n.Data)21 for _, a := range n.Attr {22 fmt.Printf(" %s=%q", a.Key, a.Val)23 }24 fmt.Printf(">\n")25 }26}27func endElement(n *html.Node) {28 if n.Type == html.ElementNode {29 fmt.Printf("</%s>\n", n.Data)30 }31}32import (33func main() {34 f, _ := os.Open("1.html")35 doc, _ := html.Parse(f)36 forEachNode(doc, startElement, endElement)37}38func forEachNode(n *html.Node, pre, post func(n *html.Node)) {39 if pre != nil {40 pre(n)41 }
Type
Using AI Code Generation
1import (2func main() {3 var reader = strings.NewReader(s)4 var doc, _ = html.Parse(reader)5 var f func(*html.Node)6 f = func(n *html.Node) {7 if n.Type == html.ElementNode {8 fmt.Println(n.Data)9 }10 for c := n.FirstChild; c != nil; c = c.NextSibling {11 f(c)12 }13 }14 f(doc)15}16import (17func main() {18 var reader = strings.NewReader(s)19 var doc, _ = html.Parse(reader)20 var f func(*html.Node)21 f = func(n *html.Node) {22 if n.Type == html.ElementNode {23 fmt.Println(n.Data)24 }25 for c := n.FirstChild; c != nil; c = c.NextSibling {26 f(c)27 }28 }29 f(doc)30}31import (32func main() {33 var reader = strings.NewReader(s)34 var doc, _ = html.Parse(reader)35 var f func(*html.Node)36 f = func(n *html.Node) {37 if n.Type == html.ElementNode {38 fmt.Println(n.Data)39 }40 for c := n.FirstChild; c != nil; c = c.NextSibling {41 f(c)42 }43 }44 f(doc)45}46import (47func main() {48 var reader = strings.NewReader(s)49 var doc, _ = html.Parse(reader)50 var f func(*html.Node)51 f = func(n *html.Node) {52 if n.Type == html.ElementNode {53 fmt.Println(n.Data)54 }55 for c := n.FirstChild; c != nil; c = c.NextSibling {56 f(c)57 }58 }59 f(doc)60}
Type
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "Exercise 5.1: %v\n", err)6 os.Exit(1)7 }8 forEachNode(doc, startElement, endElement)9}10func forEachNode(n *html.Node, pre, post func(n *html.Node)) {11 if pre != nil {12 pre(n)13 }14 for cur := n.FirstChild; cur != nil; cur = cur.NextSibling {15 forEachNode(cur, pre, post)16 }17 if post != nil {18 post(n)19 }20}21func startElement(n *html.Node) {22 if n.Type == html.ElementNode {23 fmt.Printf("<%s", n.Data)24 for _, a := range n.Attr {25 fmt.Printf(" %s='%s'", a.Key, a.Val)26 }27 fmt.Printf(">\n")28 }29}30func endElement(n *html.Node) {31 if n.Type == html.ElementNode {32 fmt.Printf("</%s>\n", n.Data)33 }34}
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!!