1
0
Fork 0
miniflux/reader/scraper/scraper.go

102 lines
2.3 KiB
Go
Raw Normal View History

// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-08-25 00:51:50 -04:00
package scraper // import "miniflux.app/reader/scraper"
import (
"errors"
"fmt"
2017-12-10 23:51:04 -05:00
"io"
"strings"
2018-08-25 00:51:50 -04:00
"miniflux.app/http/client"
"miniflux.app/logger"
"miniflux.app/reader/readability"
"miniflux.app/url"
2017-12-10 23:51:04 -05:00
"github.com/PuerkitoBio/goquery"
)
// Fetch downloads a web page and returns relevant contents.
func Fetch(websiteURL, rules, userAgent string) (string, error) {
2018-04-28 13:51:07 -04:00
clt := client.New(websiteURL)
if userAgent != "" {
clt.WithUserAgent(userAgent)
}
2018-04-28 13:51:07 -04:00
response, err := clt.Get()
if err != nil {
return "", err
}
if response.HasServerFailure() {
return "", errors.New("scraper: unable to download web page")
}
if !isWhitelistedContentType(response.ContentType) {
return "", fmt.Errorf("scraper: this resource is not a HTML document (%s)", response.ContentType)
}
if err = response.EnsureUnicodeBody(); err != nil {
return "", err
}
// The entry URL could redirect somewhere else.
2017-12-14 00:30:40 -05:00
websiteURL = response.EffectiveURL
2017-12-10 23:51:04 -05:00
if rules == "" {
rules = getPredefinedScraperRules(websiteURL)
}
var content string
2017-12-10 23:51:04 -05:00
if rules != "" {
logger.Debug(`[Scraper] Using rules %q for %q`, rules, websiteURL)
content, err = scrapContent(response.Body, rules)
2017-12-10 23:51:04 -05:00
} else {
2018-12-02 23:51:06 -05:00
logger.Debug(`[Scraper] Using readability for %q`, websiteURL)
content, err = readability.ExtractContent(response.Body)
2017-12-10 23:51:04 -05:00
}
if err != nil {
return "", err
}
return content, nil
}
2017-12-10 23:51:04 -05:00
func scrapContent(page io.Reader, rules string) (string, error) {
document, err := goquery.NewDocumentFromReader(page)
if err != nil {
return "", err
}
contents := ""
document.Find(rules).Each(func(i int, s *goquery.Selection) {
var content string
content, _ = goquery.OuterHtml(s)
2017-12-10 23:51:04 -05:00
contents += content
})
return contents, nil
}
func getPredefinedScraperRules(websiteURL string) string {
urlDomain := url.Domain(websiteURL)
for domain, rules := range predefinedRules {
if strings.Contains(urlDomain, domain) {
return rules
}
}
return ""
}
func isWhitelistedContentType(contentType string) bool {
contentType = strings.ToLower(contentType)
return strings.HasPrefix(contentType, "text/html") ||
strings.HasPrefix(contentType, "application/xhtml+xml")
}