Usage is simple. Use Gumbo to parse an HTML string into a document, create a Selector from a string, and then use eachmatch to get the nodes in the document that match the selector. Alternatively, use sel"<selector string>" to do the same thing as Selector. The eachmatch function returns an array of elements which match the selector. If no match is found, a zero element array is returned. For unique matches, the array contains one element. Thus, check the length of the array to test whether a selector matches.
using Cascadia
using Gumbo
n=parsehtml("<p id=\"foo\"><p id=\"bar\">")
s=Selector("#foo")
sm =sel"#foo"eachmatch(s, n.root)
# 1-element Array{Gumbo.HTMLNode,1}:# Gumbo.HTMLElement{:p}eachmatch(sm, n.root)
# 1-element Array{Gumbo.HTMLNode,1}:# Gumbo.HTMLElement{:p}
Note: The top level matching function name has changed from matchall in v0.6 to eachmatch in v0.7 and higher to reflect the change in Julia base.
Webscraping Example
The primary use case for this library is to enable webscraping -- the automatic extraction of information from html pages. As an example, consider the following code, which returns a list of questions that have been tagged with julia-lang on StackOverflow.
using Cascadia, Gumbo, HTTP
r = HTTP.get("http://stackoverflow.com/questions/tagged/julia-lang")
h =parsehtml(String(r.body))
qs =eachmatch(Selector(".question-summary"),h.root)
println("StackOverflow Julia Questions (votes answered? url)")
for q in qs
votes =nodeText(eachmatch(Selector(".votes .vote-count-post "), q)[1])
answered =length(eachmatch(Selector(".status.answered"), q)) >0||length(eachmatch(Selector(".status.answered-accepted"), q)) >0
href =eachmatch(Selector(".question-hyperlink"), q)[1].attributes["href"]
println("$votes$answered http://stackoverflow.com$href")
end
Note that this returns the elements on the first page of the query results. Getting the values from subsequent pages is left as an exercise for the reader.
Current Status
This library should work with almost all CSS selectors. Please raise an issue if you find any that don't work. However, note that CSS pseudo elements are not yet supported.
Specifically, the following selector types are tested, and known to work.
请发表评论