net.html: add Tag.get_tags() (#13102)

pull/13109/head
kahsa 2022-01-09 23:07:12 +09:00 committed by GitHub
parent 92fcb82ca3
commit e2a0046849
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 73 additions and 0 deletions

View File

@ -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
}

View File

@ -0,0 +1,37 @@
module html
const (
html = '<!doctype html>
<html>
<head></head>
<body>
<div id="1st">
<div class="bar"></div>
</div>
<div id="2nd">
<div class="foo">
<a href="https://vlang.io/">V</a>
</div>
<div class="bar"></div>
<a href="https://modules.vlang.io/">vlib</a>
<div class="bar">
<div class="bar">
<p>
<div>modules</div>
</p>
<a href="https://vpm.vlang.io/">vpm</a>
</div>
</div>
</div>
<div id="3rd"></div>
</body>
</html>'
)
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
}