Skip to content

Commit

Permalink
Merge pull request #33 from dustmop/any-tag-name
Browse files Browse the repository at this point in the history
Find/FindAll with an empty string will match any tag
  • Loading branch information
anaskhan96 authored May 17, 2019
2 parents ff61f0b + 38228ba commit b32d4fb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions soup.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,14 @@ func (r Root) FullText() string {
return buf.String()
}

func matchElementName(n *html.Node, name string) bool {
return name == "" || name == n.Data
}

// 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 uni == true {
if n.Type == html.ElementNode && n.Data == args[0] {
if n.Type == html.ElementNode && matchElementName(n, args[0]) {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
Expand Down Expand Up @@ -353,7 +357,7 @@ func findAllofem(n *html.Node, args []string, strict bool) []*html.Node {
var f func(*html.Node, []string, bool)
f = func(n *html.Node, args []string, uni bool) {
if uni == true {
if n.Data == args[0] {
if matchElementName(n, args[0]) {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
Expand Down
17 changes: 17 additions & 0 deletions soup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ func TestFind(t *testing.T) {
if !reflect.DeepEqual(actual, "Just two divs peacing out") {
t.Error("Instead of `Just two divs peacing out`, got", actual)
}
// Find("") for any
actual = multipleClasses.Find("body").Find("").Text()
if !reflect.DeepEqual(actual, "Multiple classes") {
t.Error("Instead of `Multiple classes`, got", actual)
}
// Find("") with attributes
actual = doc.Find("", "id", "4").Text()
if !reflect.DeepEqual(actual, "Last one") {
t.Error("Instead of `Last one`, got", actual)
}
}

func TestFindNextPrevElement(t *testing.T) {
Expand Down Expand Up @@ -131,6 +141,13 @@ func TestFindAllBySingleClass(t *testing.T) {
}
}

func TestFindAllByAttribute(t *testing.T) {
actual := doc.FindAll("", "id", "2")
if len(actual) != 1 {
t.Errorf("Expected 1 element to be returned. Actual: %d", len(actual))
}
}

func TestFindBySingleClass(t *testing.T) {
actual := multipleClasses.Find("div", "class", "first")
if actual.Text() != "Multiple classes" {
Expand Down

0 comments on commit b32d4fb

Please sign in to comment.