-
Notifications
You must be signed in to change notification settings - Fork 13
/
readability.go
2085 lines (1728 loc) · 61.4 KB
/
readability.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 (
"fmt"
"io"
"math"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"golang.org/x/net/html"
)
// All of the regular expressions in use within readability.
// Defined up here so we don't instantiate them repeatedly in loops.
var rxUnlikelyCandidates = regexp.MustCompile(`(?i)-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|foot|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote`)
var rxOkMaybeItsACandidate = regexp.MustCompile(`(?i)and|article|body|column|main|shadow`)
var rxPositive = regexp.MustCompile(`(?i)article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story`)
var rxNegative = regexp.MustCompile(`(?i)hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget`)
var rxByline = regexp.MustCompile(`(?i)byline|author|dateline|writtenby|p-author`)
var rxNormalize = regexp.MustCompile(`(?i)\s{2,}`)
var rxVideos = regexp.MustCompile(`(?i)//(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)`)
var rxWhitespace = regexp.MustCompile(`(?i)^\s*$`)
var rxHasContent = regexp.MustCompile(`(?i)\S$`)
var rxPropertyPattern = regexp.MustCompile(`(?i)\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|site_name|image\S*)\s*`)
var rxNamePattern = regexp.MustCompile(`(?i)^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name|image)\s*$`)
var rxTitleSeparator = regexp.MustCompile(`(?i) [\|\-\\/>»] `)
var rxTitleHierarchySep = regexp.MustCompile(`(?i) [\\/>»] `)
var rxTitleRemoveFinalPart = regexp.MustCompile(`(?i)(.*)[\|\-\\/>»] .*`)
var rxTitleRemove1stPart = regexp.MustCompile(`(?i)[^\|\-\\/>»]*[\|\-\\/>»](.*)`)
var rxTitleAnySeparator = regexp.MustCompile(`(?i)[\|\-\\/>»]+`)
var rxDisplayNone = regexp.MustCompile(`(?i)display\s*:\s*none`)
var rxSentencePeriod = regexp.MustCompile(`(?i)\.( |$)`)
var rxShare = regexp.MustCompile(`(?i)share`)
var rxFaviconSize = regexp.MustCompile(`(?i)(\d+)x(\d+)`)
// divToPElems is a list of HTML tag names representing content dividers.
var divToPElems = []string{
"a", "blockquote", "div", "dl", "img",
"ol", "p", "pre", "select", "table", "ul",
}
// alterToDivExceptions is a list of HTML tags that we want to convert into
// regular DIV elements to prevent unwanted removal when the parser is cleaning
// out unnecessary Nodes.
var alterToDivExceptions = []string{
"article",
"div",
"p",
"section",
}
// presentationalAttributes is a list of HTML attributes used to style Nodes.
var presentationalAttributes = []string{
"align",
"background",
"bgcolor",
"border",
"cellpadding",
"cellspacing",
"frame",
"hspace",
"rules",
"style",
"valign",
"vspace",
}
// deprecatedSizeAttributeElems is a list of HTML tags that allow programmers
// to set Width and Height attributes to define their own size but that have
// already been deprecated in recent HTML specifications.
var deprecatedSizeAttributeElems = []string{
"table",
"th",
"td",
"hr",
"pre",
}
// The commented out elements qualify as phrasing content but tend to be
// removed by readability when put into paragraphs, so we ignore them here.
var phrasingElems = []string{
// "canvas", "iframe", "svg", "video",
"abbr", "audio", "b", "bdo", "br", "button", "cite", "code", "data",
"datalist", "dfn", "em", "embed", "i", "img", "input", "kbd", "label",
"mark", "math", "meter", "noscript", "object", "output", "progress", "q",
"ruby", "samp", "script", "select", "small", "span", "strong", "sub",
"sup", "textarea", "time", "var", "wbr",
}
// flags is flags that used by parser.
type flags struct {
stripUnlikelys bool
useWeightClasses bool
cleanConditionally bool
}
// parseAttempt is container for the result of previous parse attempts.
type parseAttempt struct {
articleContent *html.Node
textLength int
}
// Article represents the metadata and content of the article.
type Article struct {
// Title is the heading that preceeds the article’s content, and the basis
// for the article’s page name and URL. It indicates what the article is
// about, and distinguishes it from other articles. The title may simply
// be the name of the subject of the article, or it may be a description
// of the topic.
Title string
// Byline is a printed line of text accompanying a news story, article, or
// the like, giving the author’s name
Byline string
// Dir is the direction of the text in the article.
//
// Either Left-to-Right (LTR) or Right-to-Left (RTL).
Dir string
// Content is the relevant text in the article with HTML tags.
Content string
// TextContent is the relevant text in the article without HTML tags.
TextContent string
// Excerpt is the summary for the relevant text in the article.
Excerpt string
// SiteName is the name of the original publisher website.
SiteName string
// Favicon (short for favorite icon) is a file containing one or more small
// icons, associated with a particular website or web page. A web designer
// can create such an icon and upload it to a website (or web page) by
// several means, and graphical web browsers will then make use of it.
Favicon string
// Image is an image URL which represents the article’s content.
Image string
// Length is the amount of characters in the article.
Length int
// Node is the first element in the HTML document.
Node *html.Node
}
// Readability is an HTML parser that reads and extract relevant content.
type Readability struct {
doc *html.Node
documentURI *url.URL
articleTitle string
articleByline string
attempts []parseAttempt
flags flags
// MaxElemsToParse is the optional maximum number of HTML nodes to parse
// from the document. If the number of elements in the document is higher
// than this number, the operation immediately errors.
MaxElemsToParse int
// NTopCandidates is the number of top candidates to consider when the
// parser is analysing how tight the competition is among candidates.
NTopCandidates int
// CharThresholds is the default number of chars an article must have in
// order to return a result.
CharThresholds int
// ClassesToPreserve are the classes that readability sets itself.
ClassesToPreserve []string
// TagsToScore is element tags to score by default.
TagsToScore []string
KeepClasses bool
}
// New returns new Readability with sane defaults to parse simple documents.
func New() *Readability {
return &Readability{
MaxElemsToParse: 0,
NTopCandidates: 5,
CharThresholds: 500,
ClassesToPreserve: []string{"page"},
TagsToScore: []string{"section", "h2", "h3", "h4", "h5", "h6", "p", "td", "pre"},
KeepClasses: false,
}
}
// removeNodes iterates over a collection of HTML elements, calls the optional
// filter function on each node, and removes the node if function returns True.
// If function is not passed, removes all the nodes in the list.
func (r *Readability) removeNodes(list []*html.Node, filter func(*html.Node) bool) {
var node *html.Node
var parentNode *html.Node
for i := len(list) - 1; i >= 0; i-- {
node = list[i]
parentNode = node.Parent
if parentNode != nil && (filter == nil || filter(node)) {
parentNode.RemoveChild(node)
}
}
}
// replaceNodeTags iterates over a list, and calls setNodeTag for each node.
func (r *Readability) replaceNodeTags(list []*html.Node, newTagName string) {
for i := len(list) - 1; i >= 0; i-- {
r.setNodeTag(list[i], newTagName)
}
}
// forEachNode iterates over a list of HTML nodes, which doesn’t natively fully
// implement the Array interface. For convenience, the current object context
// is applied to the provided iterate function.
func (r *Readability) forEachNode(list []*html.Node, fn func(*html.Node, int)) {
for idx, node := range list {
fn(node, idx)
}
}
// someNode iterates over a NodeList, return true if any of the
// provided iterate function calls returns true, false otherwise.
func (r *Readability) someNode(nodeList []*html.Node, fn func(*html.Node) bool) bool {
for i := 0; i < len(nodeList); i++ {
if fn(nodeList[i]) {
return true
}
}
return false
}
// everyNode iterates over a collection of nodes, returns true if all of the
// provided iterator function calls return true, otherwise returns false. For
// convenience, the current object context is applied to the provided iterator
// function.
func (r *Readability) everyNode(list []*html.Node, fn func(*html.Node) bool) bool {
for _, node := range list {
if !fn(node) {
return false
}
}
return true
}
// concatNodeLists concats all nodelists passed as arguments.
func (r *Readability) concatNodeLists(nodeLists ...[]*html.Node) []*html.Node {
var result []*html.Node
for i := 0; i < len(nodeLists); i++ {
result = append(result, nodeLists[i]...)
}
return result
}
func (r *Readability) getAllNodesWithTag(node *html.Node, tagNames ...string) []*html.Node {
var list []*html.Node
for _, tag := range tagNames {
list = append(list, getElementsByTagName(node, tag)...)
}
return list
}
// getArticleTitle attempts to get the article title.
func (r *Readability) getArticleTitle() string {
doc := r.doc
curTitle := ""
origTitle := ""
titleHadHierarchicalSeparators := false
// If they had an element with tag "title" in their HTML
if nodes := getElementsByTagName(doc, "title"); len(nodes) > 0 {
origTitle = r.getInnerText(nodes[0], true)
curTitle = origTitle
}
// If there's a separator in the title, first remove the final part
if rxTitleSeparator.MatchString(curTitle) {
titleHadHierarchicalSeparators = rxTitleHierarchySep.MatchString(curTitle)
curTitle = rxTitleRemoveFinalPart.ReplaceAllString(origTitle, "$1")
// If the resulting title is too short (3 words or fewer), remove
// the first part instead:
if wordCount(curTitle) < 3 {
curTitle = rxTitleRemove1stPart.ReplaceAllString(origTitle, "$1")
}
} else if strings.Index(curTitle, ": ") != -1 {
// Check if we have an heading containing this exact string, so
// we could assume it's the full title.
headings := r.concatNodeLists(
getElementsByTagName(doc, "h1"),
getElementsByTagName(doc, "h2"),
)
trimmedTitle := strings.TrimSpace(curTitle)
match := r.someNode(headings, func(heading *html.Node) bool {
return strings.TrimSpace(textContent(heading)) == trimmedTitle
})
// If we don't, let's extract the title out of the original
// title string.
if !match {
curTitle = origTitle[strings.LastIndex(origTitle, ":")+1:]
// If the title is now too short, try the first colon instead:
if wordCount(curTitle) < 3 {
curTitle = origTitle[strings.Index(origTitle, ":")+1:]
// 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 if wordCount(origTitle[:strings.Index(origTitle, ":")]) > 5 {
curTitle = origTitle
}
}
} else if len(curTitle) > 150 || len(curTitle) < 15 {
if hOnes := getElementsByTagName(doc, "h1"); len(hOnes) == 1 {
curTitle = r.getInnerText(hOnes[0], true)
}
}
curTitle = strings.TrimSpace(curTitle)
curTitle = rxNormalize.ReplaceAllString(curTitle, "\x20")
// 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 := wordCount(curTitle)
tmpOrigTitle := rxTitleAnySeparator.ReplaceAllString(origTitle, "")
if curTitleWordCount <= 4 &&
(!titleHadHierarchicalSeparators ||
curTitleWordCount != wordCount(tmpOrigTitle)-1) {
curTitle = origTitle
}
return curTitle
}
// getArticleFavicon attempts to get high quality favicon
// that used in article. It will only pick favicon in PNG
// format, so small favicon that uses ico file won't be picked.
// Using algorithm by philippe_b.
func (r *Readability) getArticleFavicon() string {
favicon := ""
faviconSize := -1
linkElements := getElementsByTagName(r.doc, "link")
r.forEachNode(linkElements, func(link *html.Node, _ int) {
linkRel := strings.TrimSpace(getAttribute(link, "rel"))
linkType := strings.TrimSpace(getAttribute(link, "type"))
linkHref := strings.TrimSpace(getAttribute(link, "href"))
linkSizes := strings.TrimSpace(getAttribute(link, "sizes"))
if linkHref == "" || !strings.Contains(linkRel, "icon") {
return
}
if linkType != "image/png" && !strings.Contains(linkHref, ".png") {
return
}
size := 0
for _, sizesLocation := range []string{linkSizes, linkHref} {
sizeParts := rxFaviconSize.FindStringSubmatch(sizesLocation)
if len(sizeParts) != 3 || sizeParts[1] != sizeParts[2] {
continue
}
size, _ = strconv.Atoi(sizeParts[1])
break
}
if size > faviconSize {
faviconSize = size
favicon = linkHref
}
})
return toAbsoluteURI(favicon, r.documentURI)
}
// prepDocument prepares the HTML document for readability to scrape it. This
// includes things like stripping JavaScript, CSS, and handling terrible markup
// among other things.
func (r *Readability) prepDocument() {
doc := r.doc
r.removeNodes(getElementsByTagName(doc, "style"), nil)
if n := getElementsByTagName(doc, "body"); len(n) > 0 && n[0] != nil {
r.replaceBrs(n[0])
}
r.replaceNodeTags(getElementsByTagName(doc, "font"), "SPAN")
}
// nextElement finds the next element, starting from the given node, and
// ignoring whitespace in between. If the given node is an element, the same
// node is returned.
func (r *Readability) nextElement(node *html.Node) *html.Node {
next := node
for next != nil &&
next.Type != html.ElementNode &&
rxWhitespace.MatchString(textContent(next)) {
next = next.NextSibling
}
return next
}
// replaceBrs replaces two 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 (r *Readability) replaceBrs(elem *html.Node) {
r.forEachNode(r.getAllNodesWithTag(elem, "br"), func(br *html.Node, _ int) {
next := br.NextSibling
// Whether two or more <br> elements have been found and replaced with
// a <p> block.
replaced := false
// If we find a <br> chain, remove the <br> nodes until we hit another
// element or non-whitespace. This leaves behind the first <br> in the
// chain (which will be replaced with a <p> later).
for {
next = r.nextElement(next)
if next == nil || tagName(next) == "BR" {
break
}
replaced = true
brSibling := next.NextSibling
next.Parent.RemoveChild(next)
next = brSibling
}
// If we removed a <br> chain, replace the remaining <br> with a <p>.
// Add all sibling nodes as children of the <p> until we hit another
// <br> chain.
if replaced {
p := createElement("p")
replaceNode(br, p)
next = p.NextSibling
for next != nil {
// If we have hit another <br><br>, we are done adding children
// to this <p>.
if tagName(next) == "br" {
nextElem := r.nextElement(next.NextSibling)
if nextElem != nil && tagName(nextElem) == "br" {
break
}
}
if !r.isPhrasingContent(next) {
break
}
// Otherwise, make this node a child of the new <p>.
sibling := next.NextSibling
appendChild(p, next)
next = sibling
}
for p.LastChild != nil && r.isWhitespace(p.LastChild) {
p.RemoveChild(p.LastChild)
}
if tagName(p.Parent) == "P" {
r.setNodeTag(p.Parent, "div")
}
}
})
}
func (r *Readability) setNodeTag(node *html.Node, newTagName string) {
if node.Type == html.ElementNode {
node.Data = newTagName
}
// NOTES(cixtor): the original function in Readability.js is a bit longer
// because it contains a fallback mechanism to set the node tag name just
// in case JSDOMParser is not available, there is no need to implement this
// here.
}
// getArticleMetadata attempts to get excerpt and byline metadata for the article.
func (r *Readability) getArticleMetadata() Article {
values := make(map[string]string)
metaElements := getElementsByTagName(r.doc, "meta")
// Find description tags.
r.forEachNode(metaElements, func(element *html.Node, _ int) {
elementName := getAttribute(element, "name")
elementProperty := getAttribute(element, "property")
content := getAttribute(element, "content")
if content == "" {
return
}
matches := []string{}
name := ""
if elementProperty != "" {
matches = rxPropertyPattern.FindAllString(elementProperty, -1)
for i := len(matches) - 1; i >= 0; i-- {
// Convert to lowercase, and remove any whitespace
// so we can match belops.
name = strings.ToLower(matches[i])
name = strings.Join(strings.Fields(name), "")
// multiple authors
values[name] = strings.TrimSpace(content)
}
}
if len(matches) == 0 && elementName != "" && rxNamePattern.MatchString(elementName) {
// Convert to lowercase, remove any whitespace, and convert
// dots to colons so we can match belops.
name = strings.ToLower(elementName)
name = strings.Join(strings.Fields(name), "")
name = strings.Replace(name, ".", ":", -1)
values[name] = strings.TrimSpace(content)
}
})
// get title
metadataTitle := ""
for _, name := range []string{
"dc:title",
"dcterm:title",
"og:title",
"weibo:article:title",
"weibo:webpage:title",
"title",
"twitter:title",
} {
if value, ok := values[name]; ok {
metadataTitle = value
break
}
}
if metadataTitle == "" {
metadataTitle = r.getArticleTitle()
}
// get author
metadataByline := ""
for _, name := range []string{
"dc:creator",
"dcterm:creator",
"author",
} {
if value, ok := values[name]; ok {
metadataByline = value
break
}
}
// get description
metadataExcerpt := ""
for _, name := range []string{
"dc:description",
"dcterm:description",
"og:description",
"weibo:article:description",
"weibo:webpage:description",
"description",
"twitter:description",
} {
if value, ok := values[name]; ok {
metadataExcerpt = value
break
}
}
// get site name
metadataSiteName := values["og:site_name"]
// get image thumbnail
metadataImage := ""
for _, name := range []string{
"og:image",
"image",
"twitter:image",
} {
if value, ok := values[name]; ok {
metadataImage = toAbsoluteURI(value, r.documentURI)
break
}
}
// get favicon
metadataFavicon := r.getArticleFavicon()
return Article{
Title: metadataTitle,
Byline: metadataByline,
Excerpt: metadataExcerpt,
SiteName: metadataSiteName,
Image: metadataImage,
Favicon: metadataFavicon,
}
}
// prepArticle prepares the article Node for display cleaning out any inline
// CSS styles, iframes, forms and stripping extraneous paragraph tags <p>.
func (r *Readability) prepArticle(articleContent *html.Node) {
r.cleanStyles(articleContent)
// 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.).
r.markDataTables(articleContent)
// Clean out junk from the article content
r.cleanConditionally(articleContent, "form")
r.cleanConditionally(articleContent, "fieldset")
r.clean(articleContent, "object")
r.clean(articleContent, "embed")
r.clean(articleContent, "footer")
r.clean(articleContent, "link")
r.clean(articleContent, "aside")
// 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".
r.forEachNode(children(articleContent), func(topCandidate *html.Node, _ int) {
r.cleanMatchedNodes(topCandidate, func(node *html.Node, nodeClassID string) bool {
return rxShare.MatchString(nodeClassID) && len(textContent(node)) < r.CharThresholds
})
})
// 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.
if h2s := getElementsByTagName(articleContent, "h2"); len(h2s) == 1 {
h2 := h2s[0]
h2Text := textContent(h2)
lengthSimilarRate := float64(len(h2Text)-len(r.articleTitle)) / float64(len(r.articleTitle))
if math.Abs(lengthSimilarRate) < 0.5 {
titlesMatch := false
if lengthSimilarRate > 0 {
titlesMatch = strings.Contains(h2Text, r.articleTitle)
} else {
titlesMatch = strings.Contains(r.articleTitle, h2Text)
}
if titlesMatch {
r.clean(articleContent, "h2")
}
}
}
r.clean(articleContent, "iframe")
r.clean(articleContent, "input")
r.clean(articleContent, "textarea")
r.clean(articleContent, "select")
r.clean(articleContent, "button")
r.cleanHeaders(articleContent)
// Do these last as the previous stuff may have removed junk
// that will affect these
r.cleanConditionally(articleContent, "table")
r.cleanConditionally(articleContent, "ul")
r.cleanConditionally(articleContent, "div")
// Remove extra paragraphs
r.removeNodes(getElementsByTagName(articleContent, "p"), func(p *html.Node) bool {
imgCount := len(getElementsByTagName(p, "img"))
embedCount := len(getElementsByTagName(p, "embed"))
objectCount := len(getElementsByTagName(p, "object"))
// Nasty iframes have been removed, only remain embedded videos.
iframeCount := len(getElementsByTagName(p, "iframe"))
totalCount := imgCount + embedCount + objectCount + iframeCount
return totalCount == 0 && r.getInnerText(p, false) == ""
})
r.forEachNode(getElementsByTagName(articleContent, "br"), func(br *html.Node, _ int) {
next := r.nextElement(br.NextSibling)
if next != nil && tagName(next) == "p" {
br.Parent.RemoveChild(br)
}
})
// Remove single-cell tables
r.forEachNode(getElementsByTagName(articleContent, "table"), func(table *html.Node, _ int) {
tbody := table
if r.hasSingleTagInsideElement(table, "tbody") {
tbody = firstElementChild(table)
}
if r.hasSingleTagInsideElement(tbody, "tr") {
row := firstElementChild(tbody)
if r.hasSingleTagInsideElement(row, "td") {
cell := firstElementChild(row)
newTag := "div"
if r.everyNode(childNodes(cell), r.isPhrasingContent) {
newTag = "p"
}
r.setNodeTag(cell, newTag)
replaceNode(table, cell)
}
}
})
}
// grabArticle uses 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 (r *Readability) grabArticle() *html.Node {
for {
doc := cloneNode(r.doc)
var page *html.Node
if nodes := getElementsByTagName(doc, "body"); len(nodes) > 0 {
page = nodes[0]
}
// We can not grab an article if we do not have a page.
if page == nil {
return nil
}
// 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).
var elementsToScore []*html.Node
var node = documentElement(doc)
for node != nil {
matchString := className(node) + "\x20" + id(node)
if !r.isProbablyVisible(node) {
node = r.removeAndGetNext(node)
continue
}
// Remove Node if it is a Byline.
if r.checkByline(node, matchString) {
node = r.removeAndGetNext(node)
continue
}
// Remove unlikely candidates.
nodeTagName := tagName(node)
if r.flags.stripUnlikelys {
if rxUnlikelyCandidates.MatchString(matchString) &&
!rxOkMaybeItsACandidate.MatchString(matchString) &&
!r.hasAncestorTag(node, "table", 3, nil) &&
nodeTagName != "body" &&
nodeTagName != "a" {
node = r.removeAndGetNext(node)
continue
}
}
// Remove DIV, SECTION and HEADER nodes without any content.
switch nodeTagName {
case "div",
"section",
"header",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6":
if r.isElementWithoutContent(node) {
node = r.removeAndGetNext(node)
continue
}
}
if indexOf(r.TagsToScore, nodeTagName) != -1 {
elementsToScore = append(elementsToScore, node)
}
// Convert <div> without children block level elements into <p>.
if nodeTagName == "div" {
// Put phrasing content into paragraphs.
var p *html.Node
childNode := node.FirstChild
for childNode != nil {
nextSibling := childNode.NextSibling
if r.isPhrasingContent(childNode) {
if p != nil {
appendChild(p, childNode)
} else if !r.isWhitespace(childNode) {
p = createElement("p")
appendChild(p, cloneNode(childNode))
replaceNode(childNode, p)
}
} else if p != nil {
for p.LastChild != nil && r.isWhitespace(p.LastChild) {
p.RemoveChild(p.LastChild)
}
p = nil
}
childNode = nextSibling
}
// 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 r.hasSingleTagInsideElement(node, "p") && r.getLinkDensity(node) < 0.25 {
newNode := children(node)[0]
replaceNode(node, newNode)
node = newNode
elementsToScore = append(elementsToScore, node)
} else if !r.hasChildBlockElement(node) {
r.setNodeTag(node, "p")
elementsToScore = append(elementsToScore, node)
}
}
node = r.getNextNode(node, false)
}
// Loop through all paragraphs and assign a score to them based on how
// much relevant content they have. 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.
var candidates []*html.Node
r.forEachNode(elementsToScore, func(elementToScore *html.Node, _ int) {
if elementToScore.Parent == nil || tagName(elementToScore.Parent) == "" {
return
}
// If this paragraph is less than 25 characters, don't even count it.
innerText := r.getInnerText(elementToScore, true)
if len(innerText) < 25 {
return
}
// Exclude nodes with no ancestor.
ancestors := r.getNodeAncestors(elementToScore, 3)
if len(ancestors) == 0 {
return
}
// Add a point for the paragraph itself as a base.
contentScore := 1
// Add points for any commas within this paragraph.
contentScore += strings.Count(innerText, ",")
// For every 100 characters in this paragraph, add another point. Up to 3 points.
contentScore += int(math.Min(math.Floor(float64(len(innerText))/100.0), 3.0))
// Initialize and score ancestors.
r.forEachNode(ancestors, func(ancestor *html.Node, level int) {
if tagName(ancestor) == "" || ancestor.Parent == nil || ancestor.Parent.Type != html.ElementNode {
return
}
if !r.hasContentScore(ancestor) {
r.initializeNode(ancestor)
candidates = append(candidates, ancestor)
}
// Node score divider:
// - parent: 1 (no division)
// - grandparent: 2
// - great grandparent+: ancestor level * 3
scoreDivider := 1
switch level {
case 0:
scoreDivider = 1
case 1:
scoreDivider = 2
default:
scoreDivider = level * 3
}
ancestorScore := r.getContentScore(ancestor)
ancestorScore += float64(contentScore) / float64(scoreDivider)
r.setContentScore(ancestor, ancestorScore)
})
})
// These lines are a bit different compared to Readability.js.
//
// In Readability.js, they fetch NTopCandidates utilising array method
// like `splice` and `pop`. In Go, array method like that is not as
// simple, especially since we are working with pointer. So, here we
// simply sort top candidates, and limit it to max NTopCandidates.
// 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.
for i := 0; i < len(candidates); i++ {
candidate := candidates[i]
candidateScore := r.getContentScore(candidate) * (1 - r.getLinkDensity(candidate))
r.setContentScore(candidate, candidateScore)
}
// After we have calculated scores, sort through all of the possible
// candidate nodes we found and find the one with the highest score.
sort.Slice(candidates, func(i int, j int) bool {
return r.getContentScore(candidates[i]) > r.getContentScore(candidates[j])
})
var topCandidates []*html.Node
if len(candidates) > r.NTopCandidates {
topCandidates = candidates[:r.NTopCandidates]
} else {
topCandidates = candidates
}
var topCandidate, parentOfTopCandidate *html.Node
neededToCreateTopCandidate := false
if len(topCandidates) > 0 {
topCandidate = topCandidates[0]
}
// If we still have no top candidate, just use the body as a last
// resort. We also have to copy the body node so it is something
// we can modify.
if topCandidate == nil || tagName(topCandidate) == "body" {
// Move all of the page's children into topCandidate
topCandidate = createElement("div")
neededToCreateTopCandidate = true
// Move everything (not just elements, also text nodes etc.)
// into the container so we even include text directly in the body:
kids := childNodes(page)
for i := 0; i < len(kids); i++ {
appendChild(topCandidate, kids[i])
}
appendChild(page, topCandidate)
r.initializeNode(topCandidate)
} else if topCandidate != nil {
// Find a better top candidate node if it contains (at least three)
// nodes which belong to `topCandidates` array and whose scores are
// quite closed with current `topCandidate` node.
topCandidateScore := r.getContentScore(topCandidate)
var alternativeCandidateAncestors [][]*html.Node
for i := 1; i < len(topCandidates); i++ {
if r.getContentScore(topCandidates[i])/topCandidateScore >= 0.75 {
topCandidateAncestors := r.getNodeAncestors(topCandidates[i], 0)
alternativeCandidateAncestors = append(alternativeCandidateAncestors, topCandidateAncestors)
}
}
minimumTopCandidates := 3
if len(alternativeCandidateAncestors) >= minimumTopCandidates {
parentOfTopCandidate = topCandidate.Parent
for parentOfTopCandidate != nil && tagName(parentOfTopCandidate) != "body" {
listContainingThisAncestor := 0
for ancestorIndex := 0; ancestorIndex < len(alternativeCandidateAncestors) && listContainingThisAncestor < minimumTopCandidates; ancestorIndex++ {
if includeNode(alternativeCandidateAncestors[ancestorIndex], parentOfTopCandidate) {
listContainingThisAncestor++
}
}
if listContainingThisAncestor >= minimumTopCandidates {
topCandidate = parentOfTopCandidate
break
}
parentOfTopCandidate = parentOfTopCandidate.Parent