1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-14 11:23:02 +02:00
ferret/examples/embedded.go

85 lines
1.7 KiB
Go
Raw Normal View History

2018-09-19 03:41:16 +02:00
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/MontFerret/ferret/pkg/compiler"
"github.com/MontFerret/ferret/pkg/drivers"
2018-12-22 18:24:06 +02:00
"github.com/MontFerret/ferret/pkg/drivers/cdp"
"github.com/MontFerret/ferret/pkg/drivers/http"
2018-09-19 03:41:16 +02:00
)
type Topic struct {
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
2018-09-19 03:41:16 +02:00
}
func main() {
topics, err := getTopTenTrendingTopics()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, topic := range topics {
fmt.Println(fmt.Sprintf("%s: %s %s", topic.Name, topic.Description, topic.URL))
2018-09-19 03:41:16 +02:00
}
}
func getTopTenTrendingTopics() ([]*Topic, error) {
query := `
LET doc = DOCUMENT("https://github.com/topics")
FOR el IN ELEMENTS(doc, ".py-4.border-bottom")
LIMIT 10
LET url = ELEMENT(el, "a")
LET name = ELEMENT(el, ".f3")
LET desc = ELEMENT(el, ".f5")
RETURN {
name: TRIM(name.innerText),
description: TRIM(desc.innerText),
url: "https://github.com" + url.attributes.href
}
`
comp := compiler.New()
program, err := comp.Compile(query)
if err != nil {
return nil, err
}
// create a root context
ctx := context.Background()
// enable HTML drivers
2018-12-22 18:24:06 +02:00
// by default, Ferret Runtime does not know about any HTML drivers
// all HTML manipulations are done via functions from standard library
2018-12-22 18:24:06 +02:00
// that assume that at least one driver is available
2019-02-21 16:46:36 +02:00
ctx = drivers.WithContext(ctx, cdp.NewDriver())
ctx = drivers.WithContext(ctx, http.NewDriver(), drivers.AsDefault())
out, err := program.Run(ctx)
2018-09-19 03:41:16 +02:00
if err != nil {
return nil, err
}
res := make([]*Topic, 0, 10)
err = json.Unmarshal(out, &res)
if err != nil {
return nil, err
}
return res, nil
}