From e2a00468494da675d5dcc897f7f8b21b226fc40b Mon Sep 17 00:00:00 2001 From: kahsa Date: Sun, 9 Jan 2022 23:07:12 +0900 Subject: [PATCH] net.html: add Tag.get_tags() (#13102) --- vlib/net/html/tag.v | 36 ++++++++++++++++++++++++++++++++++++ vlib/net/html/tag_test.v | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 vlib/net/html/tag_test.v diff --git a/vlib/net/html/tag.v b/vlib/net/html/tag.v index 62260c0edc..355dfcee46 100644 --- a/vlib/net/html/tag.v +++ b/vlib/net/html/tag.v @@ -66,3 +66,39 @@ pub fn (tag &Tag) str() string { } return html_str.str() } + +// get_tags retrieves all the child tags recursively in the tag that has the given tag name. +pub fn (tag &Tag) get_tags(name string) []&Tag { + mut res := []&Tag{} + for child in tag.children { + if child.name == name { + res << child + } + res << child.get_tags(name) + } + return res +} + +// get_tags_by_attribute retrieves all the child tags recursively in the tag that has the given attribute name. +pub fn (tag &Tag) get_tags_by_attribute(name string) []&Tag { + mut res := []&Tag{} + for child in tag.children { + if child.attributes[name] != '' { + res << child + } + res << child.get_tags_by_attribute(name) + } + return res +} + +// get_tags_by_attribute_value retrieves all the child tags recursively in the tag that has the given attribute name and value. +pub fn (tag &Tag) get_tags_by_attribute_value(name string, value string) []&Tag { + mut res := []&Tag{} + for child in tag.children { + if child.attributes[name] == value { + res << child + } + res << child.get_tags_by_attribute_value(name, value) + } + return res +} diff --git a/vlib/net/html/tag_test.v b/vlib/net/html/tag_test.v new file mode 100644 index 0000000000..dbf79561f5 --- /dev/null +++ b/vlib/net/html/tag_test.v @@ -0,0 +1,37 @@ +module html + +const ( + html = ' + + + +
+
+
+
+
+ V +
+
+ vlib +
+
+

+

modules
+

+ vpm +
+
+
+
+ +' +) + +fn test_search_by_tag_type() { + mut dom := parse(html.html) + tag := dom.get_tag_by_attribute_value('id', '2nd')[0] + assert tag.get_tags('div').len == 5 + assert tag.get_tags_by_attribute('href')[2].content == 'vpm' + assert tag.get_tags_by_attribute_value('class', 'bar').len == 3 +}