scraper.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package scraper // import "miniflux.app/reader/scraper"
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "miniflux.app/http/client"
  11. "miniflux.app/logger"
  12. "miniflux.app/reader/readability"
  13. "miniflux.app/url"
  14. "github.com/PuerkitoBio/goquery"
  15. )
  16. // Fetch downloads a web page a returns relevant contents.
  17. func Fetch(websiteURL, rules, userAgent string) (string, error) {
  18. clt := client.New(websiteURL)
  19. if userAgent != "" {
  20. clt.WithUserAgent(userAgent)
  21. }
  22. response, err := clt.Get()
  23. if err != nil {
  24. return "", err
  25. }
  26. if response.HasServerFailure() {
  27. return "", errors.New("scraper: unable to download web page")
  28. }
  29. if !strings.Contains(response.ContentType, "text/html") {
  30. return "", fmt.Errorf("scraper: this resource is not a HTML document (%s)", response.ContentType)
  31. }
  32. page, err := response.NormalizeBodyEncoding()
  33. if err != nil {
  34. return "", err
  35. }
  36. // The entry URL could redirect somewhere else.
  37. websiteURL = response.EffectiveURL
  38. if rules == "" {
  39. rules = getPredefinedScraperRules(websiteURL)
  40. }
  41. var content string
  42. if rules != "" {
  43. logger.Debug(`[Scraper] Using rules "%s" for "%s"`, rules, websiteURL)
  44. content, err = scrapContent(page, rules)
  45. } else {
  46. logger.Debug(`[Scraper] Using readability for "%s"`, websiteURL)
  47. content, err = readability.ExtractContent(page)
  48. }
  49. if err != nil {
  50. return "", err
  51. }
  52. return content, nil
  53. }
  54. func scrapContent(page io.Reader, rules string) (string, error) {
  55. document, err := goquery.NewDocumentFromReader(page)
  56. if err != nil {
  57. return "", err
  58. }
  59. contents := ""
  60. document.Find(rules).Each(func(i int, s *goquery.Selection) {
  61. var content string
  62. // For some inline elements, we get the parent.
  63. if s.Is("img") || s.Is("iframe") {
  64. content, _ = s.Parent().Html()
  65. } else {
  66. content, _ = s.Html()
  67. }
  68. contents += content
  69. })
  70. return contents, nil
  71. }
  72. func getPredefinedScraperRules(websiteURL string) string {
  73. urlDomain := url.Domain(websiteURL)
  74. for domain, rules := range predefinedRules {
  75. if strings.Contains(urlDomain, domain) {
  76. return rules
  77. }
  78. }
  79. return ""
  80. }