forked from go-shiori/go-readability
-
Notifications
You must be signed in to change notification settings - Fork 1
/
read.go
1455 lines (1230 loc) · 39.4 KB
/
read.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package readability
import (
"bytes"
"fmt"
ghtml "html"
"io"
"math"
"net/http"
nurl "net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
wl "github.com/abadojack/whatlanggo"
"golang.org/x/net/html"
)
var (
dataTableAttr = "XXX-DATA-TABLE"
rxSpaces = regexp.MustCompile(`(?is)\s{2,}|\n+`)
rxReplaceBrs = regexp.MustCompile(`(?is)(<br[^>]*>[ \n\r\t]*){2,}`)
rxByline = regexp.MustCompile(`(?is)byline|author|dateline|writtenby|p-author`)
rxUnlikelyCandidates = regexp.MustCompile(`(?is)banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|foot|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote|subscribe`)
rxOkMaybeItsACandidate = regexp.MustCompile(`(?is)and|article|body|column|main|shadow`)
rxUnlikelyElements = regexp.MustCompile(`(?is)(input|time|button|svg)`)
rxlikelyElements = regexp.MustCompile(`(?is)(no-svg)`)
rxDivToPElements = regexp.MustCompile(`(?is)<(a|blockquote|dl|div|img|ol|p|pre|table|ul|select)`)
rxPositive = regexp.MustCompile(`(?is)article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story|paragraph`)
rxNegative = regexp.MustCompile(`(?is)hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget`)
rxPIsSentence = regexp.MustCompile(`(?is)\.( |$)`)
rxVideos = regexp.MustCompile(`(?is)//(www\.)?(dailymotion|youtube|youtube-nocookie|player\.vimeo)\.com`)
rxKillBreaks = regexp.MustCompile(`(?is)(<br\s*/?>(\s| ?)*)+`)
rxComments = regexp.MustCompile(`(?is)<!--[^>]+-->`)
rxlinebreak = regexp.MustCompile(`\\r\\n`)
)
type candidateItem struct {
score float64
node *goquery.Selection
}
type readability struct {
html string
url *nurl.URL
candidates map[string]candidateItem
}
// Metadata is metadata of an article
type Metadata struct {
Title string
Image string
Excerpt string
Author string
MinReadTime int
MaxReadTime int
}
// Article is the content of an URL
type Article struct {
URL string
Meta Metadata
Text string
HTML string
Images []string
}
// removeScripts removes script tags from the document.
func removeScripts(doc *goquery.Document) {
doc.Find("script").Remove()
doc.Find("noscript").Remove()
}
// replaceBrs replaces 2 or more successive <br> elements with a single <p>.
// Whitespace between <br> elements are ignored. For example:
// <div>foo<br>bar<br> <br><br>abc</div>
// will become:
// <div>foo<br>bar<p>abc</p></div>
func replaceBrs(doc *goquery.Document) {
// Remove BRs in body
body := doc.Find("body")
html, _ := body.Html()
html = rxReplaceBrs.ReplaceAllString(html, "</p><p>")
// html = rxlinebreak.ReplaceAllString(html, "</p><p>")
body.SetHtml(html)
// Remove empty p
body.Find("p").Each(func(_ int, p *goquery.Selection) {
html, _ := p.Html()
html = strings.TrimSpace(html)
if html == "" {
p.Remove()
}
})
}
// prepDocument prepares the HTML document for readability to scrape it.
// This includes things like stripping JS, CSS, and handling terrible markup.
func prepDocument(doc *goquery.Document) {
// Remove all style tags in head
doc.Find("style").Remove()
// Replace all br
replaceBrs(doc)
// Replace font tags to span
doc.Find("font").Each(func(_ int, font *goquery.Selection) {
html, _ := font.Html()
font.ReplaceWithHtml("<span>" + html + "</span>")
})
}
// getArticleTitle fetchs the article title
func getArticleTitle(doc *goquery.Document) string {
// Get title tag
title := doc.Find("title").First().Text()
title = normalizeText(title)
originalTitle := title
// Create list of separator
separators := []string{`|`, `-`, `\`, `/`, `>`, `»`}
hierarchialSeparators := []string{`\`, `/`, `>`, `»`}
// If there's a separator in the title, first remove the final part
titleHadHierarchicalSeparators := false
if idx, sep := findSeparator(title, separators...); idx != -1 {
titleHadHierarchicalSeparators = hasSeparator(title, hierarchialSeparators...)
index := strings.LastIndex(originalTitle, sep)
title = originalTitle[:index]
// If the resulting title is too short (3 words or fewer), remove
// the first part instead:
if len(strings.Fields(title)) < 3 {
index = strings.Index(originalTitle, sep)
title = originalTitle[index+1:]
}
} else if strings.Contains(title, ": ") {
// Check if we have an heading containing this exact string, so we
// could assume it's the full title.
existInHeading := false
doc.Find("h1,h2").EachWithBreak(func(_ int, heading *goquery.Selection) bool {
headingText := strings.TrimSpace(heading.Text())
if headingText == title {
existInHeading = true
return false
}
return true
})
// If we don't, let's extract the title out of the original title string.
if !existInHeading {
index := strings.LastIndex(originalTitle, ":")
title = originalTitle[index+1:]
// If the title is now too short, try the first colon instead:
if len(strings.Fields(title)) < 3 {
index = strings.Index(originalTitle, ":")
title = originalTitle[:index]
// But if we have too many words before the colon there's something weird
// with the titles and the H tags so let's just use the original title instead
} else {
index = strings.Index(originalTitle, ":")
beforeColon := originalTitle[:index]
if len(strings.Fields(beforeColon)) > 5 {
title = originalTitle
}
}
}
} else if strLen(title) > 150 || strLen(title) < 15 {
hOne := doc.Find("h1").First()
if hOne != nil {
title = hOne.Text()
}
}
// If we now have 4 words or fewer as our title, and either no
// 'hierarchical' separators (\, /, > or ») were found in the original
// title or we decreased the number of words by more than 1 word, use
// the original title.
curTitleWordCount := len(strings.Fields(title))
noSeparatorWordCount := len(strings.Fields(removeSeparator(originalTitle, separators...)))
if curTitleWordCount <= 4 && (!titleHadHierarchicalSeparators || curTitleWordCount != noSeparatorWordCount-1) {
title = originalTitle
}
return normalizeText(title)
}
// getArticleMetadata attempts to get excerpt and byline metadata for the article.
func getArticleMetadata(doc *goquery.Document, base *nurl.URL) Metadata {
metadata := Metadata{}
mapAttribute := make(map[string]string)
doc.Find("meta").Each(func(_ int, meta *goquery.Selection) {
metaName, _ := meta.Attr("name")
metaProperty, _ := meta.Attr("property")
metaContent, _ := meta.Attr("content")
metaName = strings.TrimSpace(metaName)
metaProperty = strings.TrimSpace(metaProperty)
metaContent = strings.TrimSpace(metaContent)
// Fetch author name
if strings.Contains(metaName+metaProperty, "author") {
metadata.Author = metaContent
return
}
// Fetch description and title
if metaName == "title" ||
metaName == "description" ||
metaName == "twitter:title" ||
metaName == "twitter:image" ||
metaName == "twitter:description" {
if _, exist := mapAttribute[metaName]; !exist {
mapAttribute[metaName] = metaContent
}
return
}
if metaProperty == "og:description" ||
metaProperty == "og:image" ||
metaProperty == "og:title" {
if _, exist := mapAttribute[metaProperty]; !exist {
mapAttribute[metaProperty] = metaContent
}
return
}
})
// Set final image
if _, exist := mapAttribute["og:image"]; exist {
metadata.Image = mapAttribute["og:image"]
} else if _, exist := mapAttribute["twitter:image"]; exist {
metadata.Image = mapAttribute["twitter:image"]
}
if metadata.Image != "" {
metadata.Image = toAbsoluteURI(metadata.Image, base)
}
// Set final excerpt
if _, exist := mapAttribute["description"]; exist {
metadata.Excerpt = mapAttribute["description"]
} else if _, exist := mapAttribute["og:description"]; exist {
metadata.Excerpt = mapAttribute["og:description"]
} else if _, exist := mapAttribute["twitter:description"]; exist {
metadata.Excerpt = mapAttribute["twitter:description"]
}
// Set final title
metadata.Title = getArticleTitle(doc)
if metadata.Title == "" {
if _, exist := mapAttribute["og:title"]; exist {
metadata.Title = mapAttribute["og:title"]
} else if _, exist := mapAttribute["twitter:title"]; exist {
metadata.Title = mapAttribute["twitter:title"]
}
}
// Clean up the metadata
metadata.Title = normalizeText(metadata.Title)
metadata.Excerpt = normalizeText(metadata.Excerpt)
return metadata
}
// isValidByline checks whether the input string could be a byline.
// This verifies that the input is a string, and that the length
// is less than 100 chars.
func isValidByline(str string) bool {
return strLen(str) > 0 && strLen(str) < 100
}
func isElementWithoutContent(s *goquery.Selection) bool {
if s == nil {
return true
}
html, _ := s.Html()
html = strings.TrimSpace(html)
return html == ""
}
// hasSinglePInsideElement checks if this node has only whitespace and a single P element.
// Returns false if the DIV node contains non-empty text nodes
// or if it contains no P or more than 1 element.
func hasSinglePInsideElement(s *goquery.Selection) bool {
// There should be exactly 1 element child which is a P
return s.Children().Length() == 1 && s.Children().First().Is("p")
}
// hasChildBlockElement determines whether element has any children
// block level elements.
func hasChildBlockElement(s *goquery.Selection) bool {
html, _ := s.Html()
return rxDivToPElements.MatchString(html)
}
func setNodeTag(s *goquery.Selection, tag string) {
html, _ := s.Html()
newHTML := fmt.Sprintf("<%s>%s</%s>", tag, html, tag)
s.ReplaceWithHtml(newHTML)
}
func getNodeAncestors(node *goquery.Selection, maxDepth int) []*goquery.Selection {
ancestors := []*goquery.Selection{}
parent := node
for i := 0; i < maxDepth; i++ {
parent = parent.Parent()
if len(parent.Nodes) == 0 {
return ancestors
}
ancestors = append(ancestors, parent)
}
return ancestors
}
func hasAncestorTag(node *goquery.Selection, tag string, maxDepth int) (*goquery.Selection, bool) {
parent := node
if maxDepth < 0 {
maxDepth = 100
}
for i := 0; i < maxDepth; i++ {
parent = parent.Parent()
if len(parent.Nodes) == 0 {
break
}
if parent.Is(tag) {
return parent, true
}
}
return nil, false
}
// initializeNodeScore initializes a node and checks the className/id
// for special names to add to its score.
func initializeNodeScore(node *goquery.Selection) candidateItem {
contentScore := 0.0
tagName := goquery.NodeName(node)
switch strings.ToLower(tagName) {
case "article":
contentScore += 20
case "section":
contentScore += 8
case "div":
contentScore += 5
case "pre", "blockquote", "td":
contentScore += 3
case "form", "ol", "ul", "dl", "dd", "dt", "li", "address":
contentScore -= 3
case "th", "h1", "h2", "h3", "h4", "h5", "h6":
contentScore -= 5
}
contentScore += getClassWeight(node)
return candidateItem{contentScore, node}
}
// getClassWeight gets an elements class/id weight.
// Uses regular expressions to tell if this element looks good or bad.
func getClassWeight(node *goquery.Selection) float64 {
weight := 0.0
score := 45.0
if str, b := node.Attr("class"); b {
str = strings.ToLower(str)
if rxNegative.MatchString(str) {
weight -= score
}
if rxPositive.MatchString(str) {
weight += score
}
}
if str, b := node.Attr("id"); b {
str = strings.ToLower(str)
// if rxNegative.MatchString(str) {
// weight -= score
// }
if rxPositive.MatchString(str) {
weight += score
}
}
return weight
}
// getLinkDensity gets the density of links as a percentage of the content
// This is the amount of text that is inside a link divided by the total text in the node.
func getLinkDensity(node *goquery.Selection) float64 {
textLength := strLen(normalizeText(node.Text()))
if textLength == 0 {
return 0
}
linkLength := 0
node.Find("a").Each(func(_ int, link *goquery.Selection) {
linkLength += strLen(link.Text())
})
return float64(linkLength) / float64(textLength)
}
// Remove the style attribute on every e and under.
func cleanStyle(s *goquery.Selection) {
s.Find("*").Each(func(i int, s1 *goquery.Selection) {
tagName := goquery.NodeName(s1)
if strings.ToLower(tagName) == "svg" {
return
}
s1.RemoveAttr("align")
s1.RemoveAttr("background")
s1.RemoveAttr("bgcolor")
s1.RemoveAttr("border")
s1.RemoveAttr("cellpadding")
s1.RemoveAttr("cellspacing")
s1.RemoveAttr("frame")
s1.RemoveAttr("hspace")
s1.RemoveAttr("rules")
s1.RemoveAttr("style")
s1.RemoveAttr("valign")
s1.RemoveAttr("vspace")
s1.RemoveAttr("onclick")
s1.RemoveAttr("onmouseover")
s1.RemoveAttr("border")
s1.RemoveAttr("style")
if tagName != "table" && tagName != "th" && tagName != "td" &&
tagName != "hr" && tagName != "pre" {
s1.RemoveAttr("width")
s1.RemoveAttr("height")
}
})
}
// Return an object indicating how many rows and columns this table has.
func getTableRowAndColumnCount(table *goquery.Selection) (int, int) {
rows := 0
columns := 0
table.Find("tr").Each(func(_ int, tr *goquery.Selection) {
// Look for rows
strRowSpan, _ := tr.Attr("rowspan")
rowSpan, err := strconv.Atoi(strRowSpan)
if err != nil {
rowSpan = 1
}
rows += rowSpan
// Now look for columns
columnInThisRow := 0
tr.Find("td").Each(func(_ int, td *goquery.Selection) {
strColSpan, _ := tr.Attr("colspan")
colSpan, err := strconv.Atoi(strColSpan)
if err != nil {
colSpan = 1
}
columnInThisRow += colSpan
})
if columnInThisRow > columns {
columns = columnInThisRow
}
})
return rows, columns
}
// Look for 'data' (as opposed to 'layout') tables
func markDataTables(s *goquery.Selection) {
s.Find("table").Each(func(_ int, table *goquery.Selection) {
role, _ := table.Attr("role")
if role == "presentation" {
return
}
datatable, _ := table.Attr("datatable")
if datatable == "0" {
return
}
_, summaryExist := table.Attr("summary")
if summaryExist {
table.SetAttr(dataTableAttr, "1")
return
}
caption := table.Find("caption").First()
if len(caption.Nodes) > 0 && caption.Children().Length() > 0 {
table.SetAttr(dataTableAttr, "1")
return
}
// If the table has a descendant with any of these tags, consider a data table:
dataTableDescendants := []string{"col", "colgroup", "tfoot", "thead", "th"}
for _, tag := range dataTableDescendants {
if table.Find(tag).Length() > 0 {
table.SetAttr(dataTableAttr, "1")
return
}
}
// Nested tables indicate a layout table:
if table.Find("table").Length() > 0 {
return
}
nRow, nColumn := getTableRowAndColumnCount(table)
if nRow >= 10 || nColumn > 4 {
table.SetAttr(dataTableAttr, "1")
return
}
// Now just go by size entirely:
if nRow*nColumn > 10 {
table.SetAttr(dataTableAttr, "1")
return
}
})
}
// Clean an element of all tags of type "tag" if they look fishy.
// "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc.
func cleanConditionally(e *goquery.Selection, tag string) {
isList := tag == "ul" || tag == "ol"
e.Find(tag).Each(func(i int, node *goquery.Selection) {
// First check if we're in a data table, in which case don't remove it
if ancestor, hasTag := hasAncestorTag(node, "table", -1); hasTag {
if attr, _ := ancestor.Attr(dataTableAttr); attr == "1" {
return
}
}
// If it is table, remove data table marker
if tag == "table" {
node.RemoveAttr(dataTableAttr)
}
contentScore := 0.0
weight := getClassWeight(node)
if weight+contentScore < 0 {
node.Remove()
return
}
// If there are not very many commas, and the number of
// non-paragraph elements is more than paragraphs or other
// ominous signs, remove the element.
nodeText := normalizeText(node.Text())
nCommas := strings.Count(nodeText, ",")
nCommas += strings.Count(nodeText, ",")
if nCommas < 10 {
p := node.Find("p").Length()
img := node.Find("img").Length()
li := node.Find("li").Length() - 100
input := node.Find("input").Length()
embedCount := 0
node.Find("embed").Each(func(i int, embed *goquery.Selection) {
if !rxVideos.MatchString(embed.AttrOr("src", "")) {
embedCount++
}
})
contentLength := strLen(nodeText)
linkDensity := getLinkDensity(node)
_, hasFigureAncestor := hasAncestorTag(node, "figure", 3)
haveToRemove := (!isList && li > p) ||
(img > 1 && float64(p)/float64(img) < 0.5 && !hasFigureAncestor) ||
(float64(input) > math.Floor(float64(p)/3)) ||
(!isList && contentLength < 25 && (img == 0 || img > 2) && !hasFigureAncestor) ||
(!isList && weight < 25 && linkDensity > 0.2) ||
(weight >= 25 && linkDensity > 0.5) ||
((embedCount == 1 && contentLength < 75) || embedCount > 1)
if haveToRemove {
node.Remove()
}
}
})
}
// Clean a node of all elements of type "tag".
// (Unless it's a youtube/vimeo video. People love movies.)
func clean(s *goquery.Selection, tag string) {
isEmbed := tag == "object" || tag == "embed" || tag == "iframe"
s.Find(tag).Each(func(i int, target *goquery.Selection) {
attributeValues := ""
for _, attribute := range target.Nodes[0].Attr {
attributeValues += " " + attribute.Val
}
if isEmbed && rxVideos.MatchString(attributeValues) {
return
}
if isEmbed && rxVideos.MatchString(target.Text()) {
return
}
target.Remove()
})
}
// Clean out spurious headers from an Element. Checks things like classnames and link density.
func cleanHeaders(s *goquery.Selection) {
s.Find("h1,h2,h3").Each(func(_ int, s1 *goquery.Selection) {
if getClassWeight(s1) < 0 {
s1.Remove()
}
})
}
// Prepare the article node for display. Clean out any inline styles,
// iframes, forms, strip extraneous <p> tags, etc.
func prepArticle(articleContent *goquery.Selection, articleTitle string) {
if articleContent == nil {
return
}
// Check for data tables before we continue, to avoid removing items in
// those tables, which will often be isolated even though they're
// visually linked to other content-ful elements (text, images, etc.).
markDataTables(articleContent)
// Remove style attribute
cleanStyle(articleContent)
// Clean out junk from the article content
cleanConditionally(articleContent, "form")
cleanConditionally(articleContent, "fieldset")
clean(articleContent, "h1")
clean(articleContent, "object")
clean(articleContent, "embed")
clean(articleContent, "footer")
clean(articleContent, "link")
// Clean out elements have "share" in their id/class combinations from final top candidates,
// which means we don't remove the top candidates even they have "share".
articleContent.Find("*").Each(func(_ int, s *goquery.Selection) {
id, _ := s.Attr("id")
class, _ := s.Attr("class")
matchString := class + " " + id
if strings.Contains(matchString, "share") {
s.Remove()
}
})
// If there is only one h2 and its text content substantially equals article title,
// they are probably using it as a header and not a subheader,
// so remove it since we already extract the title separately.
h2s := articleContent.Find("h2")
if h2s.Length() == 1 {
h2 := h2s.First()
h2Text := normalizeText(h2.Text())
lengthSimilarRate := float64(strLen(h2Text)-strLen(articleTitle)) /
float64(strLen(articleTitle))
if math.Abs(lengthSimilarRate) < 0.5 {
titlesMatch := false
if lengthSimilarRate > 0 {
titlesMatch = strings.Contains(h2Text, articleTitle)
} else {
titlesMatch = strings.Contains(articleTitle, h2Text)
}
if titlesMatch {
h2.Remove()
}
}
}
clean(articleContent, "iframe")
clean(articleContent, "input")
clean(articleContent, "textarea")
clean(articleContent, "select")
clean(articleContent, "button")
cleanHeaders(articleContent)
// Do these last as the previous stuff may have removed junk
// that will affect these
cleanConditionally(articleContent, "table")
cleanConditionally(articleContent, "ul")
// TODO: some bugs
// cleanConditionally(articleContent, "div")
// Remove extra paragraphs
// At this point, nasty iframes have been removed, only remain embedded video ones.
articleContent.Find("p").Each(func(_ int, p *goquery.Selection) {
imgCount := p.Find("img").Length()
embedCount := p.Find("embed").Length()
objectCount := p.Find("object").Length()
iframeCount := p.Find("iframe").Length()
totalCount := imgCount + embedCount + objectCount + iframeCount
pText := normalizeText(p.Text())
if totalCount == 0 && strLen(pText) == 0 {
p.Remove()
}
})
articleContent.Find("br").Each(func(_ int, br *goquery.Selection) {
if br.Next().Is("p") {
br.Remove()
}
})
}
// grabArticle fetch the articles using a variety of metrics (content score, classname, element types),
// find the content that is most likely to be the stuff a user wants to read.
// Then return it wrapped up in a div.
func grabArticle(doc *goquery.Document, articleTitle string) (*goquery.Selection, string) {
// Create initial variable
author := ""
elementsToScore := []*goquery.Selection{}
// First, node prepping. Trash nodes that look cruddy (like ones with the
// class name "comment", etc), and turn divs into P tags where they have been
// used inappropriately (as in, where they contain no other block level elements.)
doc.Find("*").Each(func(i int, s *goquery.Selection) {
tagName := goquery.NodeName(s)
matchString := strings.ToLower(s.AttrOr("class", "") + " " + s.AttrOr("id", ""))
// If byline, remove this element
if rel := s.AttrOr("rel", ""); rel == "author" || rxByline.MatchString(matchString) {
text := s.Text()
text = strings.TrimSpace(text)
if isValidByline(text) {
author = text
s.Remove()
return
}
}
// Remove unlikely candid+ates
if rxUnlikelyCandidates.MatchString(matchString) &&
!rxOkMaybeItsACandidate.MatchString(matchString) &&
!s.Is("html") && !s.Is("article") && !s.Is("body") && !s.Is("a") &&
getClassWeight(s) <= 0 {
s.Remove()
return
}
if rxUnlikelyCandidates.MatchString(tagName) {
s.Remove()
return
}
if rxUnlikelyElements.MatchString(matchString) && !rxlikelyElements.MatchString(matchString) {
s.Remove()
return
}
if rxUnlikelyElements.MatchString(tagName) {
s.Remove()
return
}
// Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
if s.Is("div,section,header,h1,h2,h3,h4,h5,h6") && isElementWithoutContent(s) {
s.Remove()
return
}
})
doc.Find("*").Each(func(i int, s *goquery.Selection) {
if s.Is("section,h2,h3,h4,h5,h6,p,td,pre,article") {
elementsToScore = append(elementsToScore, s)
}
// Turn all divs that don't have children block level elements into p's
if s.Is("div") {
// fmt.Println(hasSinglePInsideElement(s))
// fmt.Println(!hasChildBlockElement(s))
// Sites like http://mobile.slate.com encloses each paragraph with a DIV
// element. DIVs with only a P element inside and no text content can be
// safely converted into plain P elements to avoid confusing the scoring
// algorithm with DIVs with are, in practice, paragraphs.
if hasSinglePInsideElement(s) {
newNode := s.Children().First()
s.ReplaceWithSelection(newNode)
elementsToScore = append(elementsToScore, s)
} else if !hasChildBlockElement(s) {
setNodeTag(s, "p")
elementsToScore = append(elementsToScore, s)
}
}
})
// Loop through all paragraphs, and assign a score to them based on how content-y they look.
// Then add their score to their parent node.
// A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
candidates := make(map[string]candidateItem)
for _, s := range elementsToScore {
// If this paragraph is less than 25 characters, don't even count it.
innerText := normalizeText(s.Text())
if strLen(innerText) < 25 {
continue
}
// Exclude nodes with no ancestor.
ancestors := getNodeAncestors(s, 3)
if len(ancestors) == 0 {
continue
}
// Calculate content score
// Add a point for the paragraph itself as a base.
contentScore := 1.0
// Add points for any commas within this paragraph.
contentScore += float64(strings.Count(innerText, ","))
contentScore += float64(strings.Count(innerText, ","))
// For every 100 characters in this paragraph, add another point. Up to 3 points.
contentScore += math.Min(math.Floor(float64(strLen(innerText)/100)), 3)
// Initialize and score ancestors.
for level, ancestor := range ancestors {
// Node score divider:
// - parent: 1 (no division)
// - grandparent: 2
// - great grandparent+: ancestor level * 3
scoreDivider := 0
if level == 0 {
scoreDivider = 1
} else if level == 1 {
scoreDivider = 2
} else {
scoreDivider = level * 3
}
ancestorHash := hashNode(ancestor)
if _, ok := candidates[ancestorHash]; !ok {
candidates[ancestorHash] = initializeNodeScore(ancestor)
}
candidate := candidates[ancestorHash]
candidate.score += contentScore / float64(scoreDivider)
candidates[ancestorHash] = candidate
}
}
// Scale the final candidates score based on link density. Good content
// should have a relatively small link density (5% or less) and be mostly
// unaffected by this operation.
topCandidate := candidateItem{}
for hash, candidate := range candidates {
candidate.score = candidate.score * (1 - getLinkDensity(candidate.node))
candidates[hash] = candidate
if topCandidate.node == nil || candidate.score > topCandidate.score {
topCandidate = candidate
}
}
// If we still have no top candidate, use the body as a last resort.
if topCandidate.node == nil {
body := doc.Find("body").First()
bodyHTML, _ := body.Html()
newHTML := fmt.Sprintf(`<div id="xxx-readability-body">%s<div>`, bodyHTML)
body.AppendHtml(newHTML)
tempReadabilityBody := body.Find("div#xxx-readability-body").First()
tempReadabilityBody.RemoveAttr("id")
tempHash := hashNode(tempReadabilityBody)
if _, ok := candidates[tempHash]; !ok {
candidates[tempHash] = initializeNodeScore(tempReadabilityBody)
}
topCandidate = candidates[tempHash]
}
// Create new document to save the final article content.
reader := strings.NewReader(`<div id="readability-content"></div>`)
newDoc, _ := goquery.NewDocumentFromReader(reader)
articleContent := newDoc.Find("div#readability-content").First()
// Now that we have the top candidate, look through its siblings for content
// that might also be related. Things like preambles, content split by ads
// that we removed, etc.
topCandidateClass, _ := topCandidate.node.Attr("class")
siblingScoreThreshold := math.Max(10.0, topCandidate.score*0.2)
topCandidate.node.Parent().Children().Each(func(_ int, sibling *goquery.Selection) {
appendSibling := false
if sibling.IsSelection(topCandidate.node) {
appendSibling = true
} else {
contentBonus := 0.0
siblingClass, _ := sibling.Attr("class")
if siblingClass == topCandidateClass && topCandidateClass != "" {
contentBonus += topCandidate.score * 0.2
}
siblingHash := hashNode(sibling)
if item, ok := candidates[siblingHash]; ok && item.score > siblingScoreThreshold {
appendSibling = true
} else if sibling.Is("p") {
linkDensity := getLinkDensity(sibling)
nodeContent := normalizeText(sibling.Text())
nodeLength := strLen(nodeContent)
if nodeLength > 80 && linkDensity < 0.25 {
appendSibling = true
} else if nodeLength < 80 && nodeLength > 0 &&
linkDensity == 0 && rxPIsSentence.MatchString(nodeContent) {
appendSibling = true
}
}
}
if appendSibling {
articleContent.AppendSelection(sibling)
}
})
// So we have all of the content that we need.
// Now we clean it up for presentation.
prepArticle(articleContent, articleTitle)
return articleContent, author
}
// Convert relative uri to absolute
func toAbsoluteURI(uri string, base *nurl.URL) string {
if uri == "" || base == nil {
return ""
}
// If it is hash tag, return as it is
if uri[0:1] == "#" {
return uri
}
// If it is already an absolute URL, return as it is
tempURI, err := nurl.ParseRequestURI(uri)
if err == nil && len(tempURI.Scheme) > 0 {
return uri
}
// Otherwise, put it as path of base URL
newURI := nurl.URL(*base)
resourceURI, err := nurl.Parse(uri)
if err != nil {
return uri
}
absolute := newURI.ResolveReference(resourceURI)
return absolute.String()
}
// Converts each <a> and <img> uri in the given element to an absolute URI,
// ignoring #ref URIs.
func fixRelativeURIs(articleContent *goquery.Selection, base *nurl.URL) {
articleContent.Find("a").Each(func(_ int, a *goquery.Selection) {
if href, exist := a.Attr("href"); exist {
// Replace links with javascript: URIs with text content, since
// they won't work after scripts have been removed from the page.
if strings.HasPrefix(href, "javascript:") {
text := a.Text()
a.ReplaceWithHtml(text)
} else {
a.SetAttr("href", toAbsoluteURI(href, base))
}
}
})
articleContent.Find("img").Each(func(_ int, img *goquery.Selection) {
if src, exist := img.Attr("src"); exist {
img.SetAttr("src", toAbsoluteURI(src, base))
} else if src, exist := img.Attr("data-src"); exist {