From f8f6d4dd595f7cc5ff92ca698d803afb8cb88ca7 Mon Sep 17 00:00:00 2001 From: Dzianis Lituyeu Date: Fri, 31 Mar 2023 16:24:23 +0300 Subject: [PATCH] Fix findOnce() panic --- soup.go | 6 ++++++ soup_test.go | 9 ++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/soup.go b/soup.go index 4a7e4df..9e8e100 100644 --- a/soup.go +++ b/soup.go @@ -481,6 +481,9 @@ func matchElementName(n *html.Node, name string) bool { // Using depth first search to find the first occurrence and return func findOnce(n *html.Node, args []string, uni bool, strict bool) (*html.Node, bool) { + if n == nil { + return nil, false + } if uni == true { if n.Type == html.ElementNode && matchElementName(n, args[0]) { if len(args) > 1 && len(args) < 4 { @@ -510,6 +513,9 @@ func findOnce(n *html.Node, args []string, uni bool, strict bool) (*html.Node, b // Using depth first search to find all occurrences and return func findAllofem(n *html.Node, args []string, strict bool) []*html.Node { + if n == nil { + return nil + } var nodeLinks = make([]*html.Node, 0, 10) var f func(*html.Node, []string, bool) f = func(n *html.Node, args []string, uni bool) { diff --git a/soup_test.go b/soup_test.go index d2010d4..a638c1f 100644 --- a/soup_test.go +++ b/soup_test.go @@ -2,6 +2,7 @@ package soup import ( "bytes" + "fmt" "io/ioutil" "net/http" "net/http/httptest" @@ -91,6 +92,13 @@ func TestFind(t *testing.T) { assert.Equal(t, "Last one", actual) } +func TestFindOnceReturnsNil(t *testing.T) { + // FindOnce() + tag := "some tag" + actual := doc.Find(tag) + assert.Equal(t, fmt.Sprintf("element `%s` with attributes `%s` not found", tag, ""), actual.Error.Error()) +} + func TestFindNextPrevElement(t *testing.T) { // FindNextSibling() and NodeValue field actual := doc.Find("div", "id", "0").FindNextSibling().NodeValue @@ -290,5 +298,4 @@ func TestClient_PostForm(t *testing.T) { func TestHTML(t *testing.T) { li := doc.Find("ul").Find("li") assert.Equal(t, "
  • To a JSP page right?
  • ", li.HTML()) - }