-
Notifications
You must be signed in to change notification settings - Fork 88
/
parser.go
2327 lines (2003 loc) · 74.6 KB
/
parser.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 (
"encoding/json"
"fmt"
shtml "html"
"log"
"math"
nurl "net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/go-shiori/dom"
"github.com/go-shiori/go-readability/internal/re2go"
"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 (
rxVideos = regexp.MustCompile(`(?i)//(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)`)
rxTokenize = regexp.MustCompile(`(?i)\W+`)
rxWhitespace = regexp.MustCompile(`(?i)^\s*$`)
rxHasContent = regexp.MustCompile(`(?i)\S$`)
rxHashURL = regexp.MustCompile(`(?i)^#.+`)
rxPropertyPattern = regexp.MustCompile(`(?i)\s*(dc|dcterm|og|article|twitter)\s*:\s*(author|creator|description|title|site_name|published_time|modified_time|image\S*)\s*`)
rxNamePattern = regexp.MustCompile(`(?i)^\s*(?:(dc|dcterm|article|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name|published_time|modified_time|image)\s*$`)
rxTitleSeparator = regexp.MustCompile(`(?i) [\|\-\\/>»] `)
rxTitleHierarchySep = regexp.MustCompile(`(?i) [\\/>»] `)
rxTitleRemoveFinalPart = regexp.MustCompile(`(?i)(.*)[\|\-\\/>»] .*`)
rxTitleRemove1stPart = regexp.MustCompile(`(?i)[^\|\-\\/>»]*[\|\-\\/>»](.*)`)
rxTitleAnySeparator = regexp.MustCompile(`(?i)[\|\-\\/>»]+`)
rxDisplayNone = regexp.MustCompile(`(?i)display\s*:\s*none`)
rxVisibilityHidden = regexp.MustCompile(`(?i)visibility\s*:\s*hidden`)
rxSentencePeriod = regexp.MustCompile(`(?i)\.( |$)`)
rxShareElements = regexp.MustCompile(`(?i)(\b|_)(share|sharedaddy)(\b|_)`)
rxFaviconSize = regexp.MustCompile(`(?i)(\d+)x(\d+)`)
rxLazyImageSrcset = regexp.MustCompile(`(?i)\.(jpg|jpeg|png|webp)\s+\d`)
rxLazyImageSrc = regexp.MustCompile(`(?i)^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$`)
rxImgExtensions = regexp.MustCompile(`(?i)\.(jpg|jpeg|png|webp)`)
rxSrcsetURL = regexp.MustCompile(`(?i)(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))`)
rxB64DataURL = regexp.MustCompile(`(?i)^data:\s*([^\s;,]+)\s*;\s*base64\s*,`)
rxJsonLdArticleTypes = regexp.MustCompile(`(?i)^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$`)
rxCDATA = regexp.MustCompile(`^\s*<!\[CDATA\[|\]\]>\s*$`)
rxSchemaOrg = regexp.MustCompile(`(?i)^https?\:\/\/schema\.org\/?$`)
)
// Constants that used by readability.
var (
unlikelyRoles = sliceToMap("menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog")
divToPElems = sliceToMap("blockquote", "dl", "div", "img", "ol", "p", "pre", "table", "ul", "select")
alterToDivExceptions = []string{"div", "article", "section", "p"}
presentationalAttributes = []string{"align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace"}
deprecatedSizeAttributeElems = []string{"table", "th", "td", "hr", "pre"}
phrasingElems = []string{
"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 is the final readable content.
type Article struct {
Title string
Byline string
Node *html.Node
Content string
TextContent string
Length int
Excerpt string
SiteName string
Image string
Favicon string
Language string
PublishedTime *time.Time
ModifiedTime *time.Time
}
// Parser is the parser that parses the page to get the readable content.
type Parser struct {
// MaxElemsToParse is the max number of nodes supported by this
// parser. Default: 0 (no limit)
MaxElemsToParse int
// NTopCandidates is the number of top candidates to consider when
// 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
// KeepClasses specify whether the classes should be stripped or not.
KeepClasses bool
// TagsToScore is element tags to score by default.
TagsToScore []string
// Debug determines if the log should be printed or not. Default: false.
Debug bool
// DisableJSONLD determines if metadata in JSON+LD will be extracted
// or not. Default: false.
DisableJSONLD bool
// AllowedVideoRegex is a regular expression that matches video URLs that should be
// allowed to be included in the article content. If undefined, it will use default filter.
AllowedVideoRegex *regexp.Regexp
doc *html.Node
documentURI *nurl.URL
articleTitle string
articleByline string
articleDir string
articleSiteName string
articleLang string
attempts []parseAttempt
flags flags
}
// NewParser returns new Parser which set up with default value.
func NewParser() Parser {
return Parser{
MaxElemsToParse: 0,
NTopCandidates: 5,
CharThresholds: 500,
ClassesToPreserve: []string{"page"},
KeepClasses: false,
TagsToScore: []string{"section", "h2", "h3", "h4", "h5", "h6", "p", "td", "pre"},
Debug: false,
}
}
// postProcessContent runs any post-process modifications to article
// content as necessary.
func (ps *Parser) postProcessContent(articleContent *html.Node) {
// Readability cannot open relative uris so we convert them to absolute uris.
ps.fixRelativeURIs(articleContent)
ps.simplifyNestedElements(articleContent)
// Remove classes.
if !ps.KeepClasses {
ps.cleanClasses(articleContent)
}
// Remove readability attributes.
ps.clearReadabilityAttr(articleContent)
}
// removeNodes iterates over a NodeList, calls `filterFn` for each node
// and removes node if function returned `true`. If function is not
// passed, removes all the nodes in node list.
func (ps *Parser) removeNodes(nodeList []*html.Node, filterFn func(*html.Node) bool) {
for i := len(nodeList) - 1; i >= 0; i-- {
node := nodeList[i]
parentNode := node.Parent
if parentNode != nil && (filterFn == nil || filterFn(node)) {
parentNode.RemoveChild(node)
}
}
}
// replaceNodeTags iterates over a NodeList, and calls setNodeTag for
// each node.
func (ps *Parser) replaceNodeTags(nodeList []*html.Node, newTagName string) {
for i := len(nodeList) - 1; i >= 0; i-- {
node := nodeList[i]
ps.setNodeTag(node, newTagName)
}
}
// forEachNode iterates over a NodeList and runs fn on each node.
func (ps *Parser) forEachNode(nodeList []*html.Node, fn func(*html.Node, int)) {
for i := 0; i < len(nodeList); i++ {
fn(nodeList[i], i)
}
}
// someNode iterates over a NodeList, return true if any of the
// provided iterate function calls returns true, false otherwise.
func (ps *Parser) 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 NodeList, return true if all of the
// provided iterate function calls returns true, false otherwise.
func (ps *Parser) everyNode(nodeList []*html.Node, fn func(*html.Node) bool) bool {
for i := 0; i < len(nodeList); i++ {
if !fn(nodeList[i]) {
return false
}
}
return true
}
// concatNodeLists concats all nodelists passed as arguments.
func (ps *Parser) concatNodeLists(nodeLists ...[]*html.Node) []*html.Node {
var result []*html.Node
for i := 0; i < len(nodeLists); i++ {
result = append(result, nodeLists[i]...)
}
return result
}
// getAllNodesWithTag returns all nodes that has tag inside tagNames.
func (ps *Parser) getAllNodesWithTag(node *html.Node, tagNames ...string) []*html.Node {
var result []*html.Node
for i := 0; i < len(tagNames); i++ {
result = append(result, dom.GetElementsByTagName(node, tagNames[i])...)
}
return result
}
// cleanClasses removes the class="" attribute from every element in the
// given subtree, except those that match CLASSES_TO_PRESERVE and the
// classesToPreserve array from the options object.
func (ps *Parser) cleanClasses(node *html.Node) {
nodeClassName := dom.ClassName(node)
preservedClassName := []string{}
for _, class := range strings.Fields(nodeClassName) {
if indexOf(ps.ClassesToPreserve, class) != -1 {
preservedClassName = append(preservedClassName, class)
}
}
if len(preservedClassName) > 0 {
dom.SetAttribute(node, "class", strings.Join(preservedClassName, " "))
} else {
dom.RemoveAttribute(node, "class")
}
for child := dom.FirstElementChild(node); child != nil; child = dom.NextElementSibling(child) {
ps.cleanClasses(child)
}
}
// fixRelativeURIs converts each <a> and <img> uri in the given element
// to an absolute URI, ignoring #ref URIs.
func (ps *Parser) fixRelativeURIs(articleContent *html.Node) {
links := ps.getAllNodesWithTag(articleContent, "a")
ps.forEachNode(links, func(link *html.Node, _ int) {
href := dom.GetAttribute(link, "href")
if href == "" {
return
}
// Remove links with javascript: URIs, since they won't
// work after scripts have been removed from the page.
if strings.HasPrefix(href, "javascript:") {
linkChilds := dom.ChildNodes(link)
if len(linkChilds) == 1 && linkChilds[0].Type == html.TextNode {
// If the link only contains simple text content,
// it can be converted to a text node
text := dom.CreateTextNode(dom.TextContent(link))
dom.ReplaceChild(link.Parent, text, link)
} else {
// If the link has multiple children, they should
// all be preserved
container := dom.CreateElement("span")
for link.FirstChild != nil {
dom.AppendChild(container, link.FirstChild)
}
dom.ReplaceChild(link.Parent, container, link)
}
} else {
newHref := toAbsoluteURI(href, ps.documentURI)
if newHref == "" {
dom.RemoveAttribute(link, "href")
} else {
dom.SetAttribute(link, "href", newHref)
}
}
})
medias := ps.getAllNodesWithTag(articleContent, "img", "picture", "figure", "video", "audio", "source")
ps.forEachNode(medias, func(media *html.Node, _ int) {
src := dom.GetAttribute(media, "src")
poster := dom.GetAttribute(media, "poster")
srcset := dom.GetAttribute(media, "srcset")
if src != "" {
newSrc := toAbsoluteURI(src, ps.documentURI)
dom.SetAttribute(media, "src", newSrc)
}
if poster != "" {
newPoster := toAbsoluteURI(poster, ps.documentURI)
dom.SetAttribute(media, "poster", newPoster)
}
if srcset != "" {
newSrcset := rxSrcsetURL.ReplaceAllStringFunc(srcset, func(s string) string {
p := rxSrcsetURL.FindStringSubmatch(s)
return toAbsoluteURI(p[1], ps.documentURI) + p[2] + p[3]
})
dom.SetAttribute(media, "srcset", newSrcset)
}
})
}
func (ps *Parser) simplifyNestedElements(articleContent *html.Node) {
node := articleContent
for node != nil {
nodeID := dom.ID(node)
nodeTagName := dom.TagName(node)
if node.Parent != nil && (nodeTagName == "div" || nodeTagName == "section") &&
!strings.HasPrefix(nodeID, "readability") {
if ps.isElementWithoutContent(node) {
node = ps.removeAndGetNext(node)
continue
}
if ps.hasSingleTagInsideElement(node, "div") || ps.hasSingleTagInsideElement(node, "section") {
child := dom.Children(node)[0]
for _, attr := range node.Attr {
dom.SetAttribute(child, attr.Key, attr.Val)
}
dom.ReplaceChild(node.Parent, child, node)
node = child
continue
}
}
node = ps.getNextNode(node, false)
}
}
// getArticleTitle attempts to get the article title.
func (ps *Parser) getArticleTitle() string {
doc := ps.doc
curTitle := ""
origTitle := ""
titleHadHierarchicalSeparators := false
// If they had an element with tag "title" in their HTML
if nodes := dom.GetElementsByTagName(doc, "title"); len(nodes) > 0 {
origTitle = ps.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.Contains(curTitle, ": ") {
// Check if we have an heading containing this exact string, so
// we could assume it's the full title.
headings := ps.concatNodeLists(
dom.GetElementsByTagName(doc, "h1"),
dom.GetElementsByTagName(doc, "h2"),
)
trimmedTitle := strings.TrimSpace(curTitle)
match := ps.someNode(headings, func(heading *html.Node) bool {
return strings.TrimSpace(dom.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 charCount(curTitle) > 150 || charCount(curTitle) < 15 {
if hOnes := dom.GetElementsByTagName(doc, "h1"); len(hOnes) == 1 {
curTitle = ps.getInnerText(hOnes[0], true)
}
}
curTitle = strings.TrimSpace(curTitle)
curTitle = re2go.NormalizeSpaces(curTitle)
// 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
}
// prepDocument prepares the HTML document for readability to scrape it.
// This includes things like stripping javascript, CSS, and handling
// terrible markup.
func (ps *Parser) prepDocument() {
doc := ps.doc
// ADDITIONAL, not exist in readability.js:
// Remove all comments,
ps.removeComments(doc)
// Remove all style tags in head
ps.removeNodes(dom.GetElementsByTagName(doc, "style"), nil)
if nodes := dom.GetElementsByTagName(doc, "body"); len(nodes) > 0 && nodes[0] != nil {
ps.replaceBrs(nodes[0])
}
ps.replaceNodeTags(dom.GetElementsByTagName(doc, "font"), "span")
}
// nextNode 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 (ps *Parser) nextNode(node *html.Node) *html.Node {
next := node
for next != nil && next.Type != html.ElementNode && rxWhitespace.MatchString(dom.TextContent(next)) {
next = next.NextSibling
}
return next
}
// replaceBrs replaces 2 or more successive <br> 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 (ps *Parser) replaceBrs(elem *html.Node) {
ps.forEachNode(ps.getAllNodesWithTag(elem, "br"), func(br *html.Node, _ int) {
next := br.NextSibling
// Whether 2 or more <br> elements have been found and replaced
// with a <p> block.
replaced := false
// If we find a <br> chain, remove the <br>s 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 = ps.nextNode(next)
if next == nil || dom.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 := dom.CreateElement("p")
dom.ReplaceChild(br.Parent, p, br)
next = p.NextSibling
for next != nil {
// If we've hit another <br><br>, we're done adding children to this <p>.
if dom.TagName(next) == "br" {
nextElem := ps.nextNode(next.NextSibling)
if nextElem != nil && dom.TagName(nextElem) == "br" {
break
}
}
if !ps.isPhrasingContent(next) {
break
}
// Otherwise, make this node a child of the new <p>.
sibling := next.NextSibling
dom.AppendChild(p, next)
next = sibling
}
for p.LastChild != nil && ps.isWhitespace(p.LastChild) {
p.RemoveChild(p.LastChild)
}
if dom.TagName(p.Parent) == "p" {
ps.setNodeTag(p.Parent, "div")
}
}
})
}
// setNodeTag changes tag of the node to newTagName.
func (ps *Parser) setNodeTag(node *html.Node, newTagName string) {
if node.Type == html.ElementNode {
node.Data = newTagName
}
}
// prepArticle prepares the article node for display. Clean out any
// inline styles, iframes, forms, strip extraneous <p> tags, etc.
func (ps *Parser) prepArticle(articleContent *html.Node) {
ps.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.).
ps.markDataTables(articleContent)
ps.fixLazyImages(articleContent)
// Clean out junk from the article content
ps.cleanConditionally(articleContent, "form")
ps.cleanConditionally(articleContent, "fieldset")
ps.clean(articleContent, "object")
ps.clean(articleContent, "embed")
ps.clean(articleContent, "footer")
ps.clean(articleContent, "link")
ps.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".
shareElementThreshold := ps.CharThresholds
ps.forEachNode(dom.Children(articleContent), func(topCandidate *html.Node, _ int) {
ps.cleanMatchedNodes(topCandidate, func(node *html.Node, nodeClassID string) bool {
return rxShareElements.MatchString(nodeClassID) && charCount(dom.TextContent(node)) < shareElementThreshold
})
})
ps.clean(articleContent, "iframe")
ps.clean(articleContent, "input")
ps.clean(articleContent, "textarea")
ps.clean(articleContent, "select")
ps.clean(articleContent, "button")
ps.cleanHeaders(articleContent)
// Do these last as the previous stuff may have removed junk
// that will affect these
ps.cleanConditionally(articleContent, "table")
ps.cleanConditionally(articleContent, "ul")
ps.cleanConditionally(articleContent, "div")
// Replace H1 with H2 as H1 should be only title that is displayed separately
ps.replaceNodeTags(ps.getAllNodesWithTag(articleContent, "h1"), "h2")
// Remove extra paragraphs
ps.removeNodes(dom.GetElementsByTagName(articleContent, "p"), func(p *html.Node) bool {
imgCount := len(dom.GetElementsByTagName(p, "img"))
embedCount := len(dom.GetElementsByTagName(p, "embed"))
objectCount := len(dom.GetElementsByTagName(p, "object"))
// At this point, nasty iframes have been removed, only
// remain embedded video ones.
iframeCount := len(dom.GetElementsByTagName(p, "iframe"))
totalCount := imgCount + embedCount + objectCount + iframeCount
return totalCount == 0 && ps.getInnerText(p, false) == ""
})
ps.forEachNode(dom.GetElementsByTagName(articleContent, "br"), func(br *html.Node, _ int) {
next := ps.nextNode(br.NextSibling)
if next != nil && dom.TagName(next) == "p" {
br.Parent.RemoveChild(br)
}
})
// Remove single-cell tables
ps.forEachNode(dom.GetElementsByTagName(articleContent, "table"), func(table *html.Node, _ int) {
tbody := table
if ps.hasSingleTagInsideElement(table, "tbody") {
tbody = dom.FirstElementChild(table)
}
if ps.hasSingleTagInsideElement(tbody, "tr") {
row := dom.FirstElementChild(tbody)
if ps.hasSingleTagInsideElement(row, "td") {
cell := dom.FirstElementChild(row)
newTag := "div"
if ps.everyNode(dom.ChildNodes(cell), ps.isPhrasingContent) {
newTag = "p"
}
ps.setNodeTag(cell, newTag)
dom.ReplaceChild(table.Parent, cell, table)
}
}
})
}
// initializeNode initializes a node with the readability score.
// Also checks the className/id for special names to add to its score.
func (ps *Parser) initializeNode(node *html.Node) {
contentScore := float64(ps.getClassWeight(node))
switch dom.TagName(node) {
case "div":
contentScore += 5
case "pre", "td", "blockquote":
contentScore += 3
case "address", "ol", "ul", "dl", "dd", "dt", "li", "form":
contentScore -= 3
case "h1", "h2", "h3", "h4", "h5", "h6", "th":
contentScore -= 5
}
ps.setContentScore(node, contentScore)
}
// removeAndGetNext remove node and returns its next node.
func (ps *Parser) removeAndGetNext(node *html.Node) *html.Node {
nextNode := ps.getNextNode(node, true)
if node.Parent != nil {
node.Parent.RemoveChild(node)
}
return nextNode
}
// getNextNode traverses the DOM from node to node, starting at the
// node passed in. Pass true for the second parameter to indicate
// this node itself (and its kids) are going away, and we want the
// next node over. Calling this in a loop will traverse the DOM
// depth-first.
// In Readability.js, ignoreSelfAndKids default to false.
func (ps *Parser) getNextNode(node *html.Node, ignoreSelfAndKids bool) *html.Node {
// First check for kids if those aren't being ignored
if firstChild := dom.FirstElementChild(node); !ignoreSelfAndKids && firstChild != nil {
return firstChild
}
// Then for siblings...
if sibling := dom.NextElementSibling(node); sibling != nil {
return sibling
}
// And finally, move up the parent chain *and* find a sibling
// (because this is depth-first traversal, we will have already
// seen the parent nodes themselves).
for {
node = node.Parent
if node == nil || dom.NextElementSibling(node) != nil {
break
}
}
if node != nil {
return dom.NextElementSibling(node)
}
return nil
}
// textSimilarity compares second text to first one. 1 = same text, 0 = completely different text.
// The way it works: it splits both texts into words and then finds words that are unique in
// second text the result is given by the lower length of unique parts.
func (ps *Parser) textSimilarity(textA, textB string) float64 {
tokensA := rxTokenize.Split(strings.ToLower(textA), -1)
tokensA = strFilter(tokensA, func(s string) bool { return s != "" })
mapTokensA := sliceToMap(tokensA...)
tokensB := rxTokenize.Split(strings.ToLower(textB), -1)
tokensB = strFilter(tokensB, func(s string) bool { return s != "" })
uniqueTokensB := strFilter(tokensB, func(s string) bool {
_, existInA := mapTokensA[s]
return !existInA
})
mergedB := strings.Join(tokensB, " ")
mergedUniqueB := strings.Join(uniqueTokensB, " ")
distanceB := float64(charCount(mergedUniqueB)) / float64(charCount(mergedB))
return 1 - distanceB
}
// checkByline determines if a node is used as byline.
func (ps *Parser) checkByline(node *html.Node, matchString string) bool {
if ps.articleByline != "" {
return false
}
rel := dom.GetAttribute(node, "rel")
itemprop := dom.GetAttribute(node, "itemprop")
nodeText := dom.TextContent(node)
if (rel == "author" || strings.Contains(itemprop, "author") || re2go.IsByline(matchString)) &&
ps.isValidByline(nodeText) {
nodeText = strings.TrimSpace(nodeText)
nodeText = strings.Join(strings.Fields(nodeText), " ")
ps.articleByline = nodeText
return true
}
return false
}
func (ps *Parser) getTextDensity(node *html.Node, tags ...string) float64 {
textLength := charCount(ps.getInnerText(node, true))
if textLength == 0 {
return 0
}
var childrenLength int
children := ps.getAllNodesWithTag(node, tags...)
ps.forEachNode(children, func(child *html.Node, _ int) {
childrenLength += charCount(ps.getInnerText(child, true))
})
return float64(childrenLength) / float64(textLength)
}
// getNodeAncestors gets the node's direct parent and grandparents.
// In Readability.js, maxDepth default to 0.
func (ps *Parser) getNodeAncestors(node *html.Node, maxDepth int) []*html.Node {
i := 0
var ancestors []*html.Node
for node.Parent != nil {
i++
ancestors = append(ancestors, node.Parent)
if maxDepth > 0 && i == maxDepth {
break
}
node = node.Parent
}
return ancestors
}
// 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 (ps *Parser) grabArticle() *html.Node {
ps.log("**** GRAB ARTICLE ****")
for {
doc := dom.Clone(ps.doc, true)
var page *html.Node
if nodes := dom.GetElementsByTagName(doc, "body"); len(nodes) > 0 {
page = nodes[0]
}
// We can't grab an article if we don't have a page!
if page == nil {
ps.log("no body found in document, abort")
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 = dom.DocumentElement(doc)
shouldRemoveTitleHeader := true
for node != nil {
matchString := dom.ClassName(node) + " " + dom.ID(node)
if dom.TagName(node) == "html" {
ps.articleLang = dom.GetAttribute(node, "lang")
}
if !ps.isProbablyVisible(node) {
ps.logf("removing hidden node: %q\n", matchString)
node = ps.removeAndGetNext(node)
continue
}
// User is not able to see elements applied with both "aria-modal = true"
// and "role = dialog"
if dom.GetAttribute(node, "aria-modal") == "true" &&
dom.GetAttribute(node, "role") == "dialog" {
node = ps.removeAndGetNext(node)
continue
}
// Check to see if this node is a byline, and remove it if
// it is true.
if ps.checkByline(node, matchString) {
node = ps.removeAndGetNext(node)
continue
}
if shouldRemoveTitleHeader && ps.headerDuplicatesTitle(node) {
ps.logf("removing header: %q duplicate of %q\n",
trim(dom.TextContent(node)), trim(ps.articleTitle))
shouldRemoveTitleHeader = false
node = ps.removeAndGetNext(node)
continue
}
// Remove unlikely candidates
nodeTagName := dom.TagName(node)
if ps.flags.stripUnlikelys {
if re2go.IsUnlikelyCandidates(matchString) &&
!re2go.MaybeItsACandidate(matchString) &&
!ps.hasAncestorTag(node, "table", 3, nil) &&
!ps.hasAncestorTag(node, "code", 3, nil) &&
nodeTagName != "body" && nodeTagName != "a" {
ps.logf("removing unlikely candidate: %q\n", matchString)
node = ps.removeAndGetNext(node)
continue
}
role := dom.GetAttribute(node, "role")
if _, include := unlikelyRoles[role]; include {
ps.logf("removing content with role %q: %q\n", role, matchString)
node = ps.removeAndGetNext(node)
continue
}
}
// Remove DIV, SECTION, and HEADER nodes without any
// content(e.g. text, image, video, or iframe).
switch nodeTagName {
case "div", "section", "header",
"h1", "h2", "h3", "h4", "h5", "h6":
if ps.isElementWithoutContent(node) {
node = ps.removeAndGetNext(node)
continue
}
}
if indexOf(ps.TagsToScore, nodeTagName) != -1 {
elementsToScore = append(elementsToScore, node)
}
// Turn all divs that don't have children block level
// elements into p's
if nodeTagName == "div" {
// Put phrasing content into paragraphs.
var p *html.Node
childNode := node.FirstChild
for childNode != nil {
nextSibling := childNode.NextSibling
if ps.isPhrasingContent(childNode) {
if p != nil {
dom.AppendChild(p, childNode)
} else if !ps.isWhitespace(childNode) {
p = dom.CreateElement("p")
dom.AppendChild(p, dom.Clone(childNode, true))
dom.ReplaceChild(node, p, childNode)
}
} else if p != nil {
for p.LastChild != nil && ps.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 ps.hasSingleTagInsideElement(node, "p") && ps.getLinkDensity(node) < 0.25 {
newNode := dom.Children(node)[0]
node, _ = dom.ReplaceChild(node.Parent, newNode, node)
elementsToScore = append(elementsToScore, node)
} else if !ps.hasChildBlockElement(node) {
ps.setNodeTag(node, "p")
elementsToScore = append(elementsToScore, node)
}
}
node = ps.getNextNode(node, false)
}
// 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.
var candidates []*html.Node
ps.forEachNode(elementsToScore, func(elementToScore *html.Node, _ int) {
if elementToScore.Parent == nil || dom.TagName(elementToScore.Parent) == "" {
return
}
// If this paragraph is less than 25 characters, don't even count it.
innerText := ps.getInnerText(elementToScore, true)
if charCount(innerText) < 25 {
return
}
// Exclude nodes with no ancestor.
ancestors := ps.getNodeAncestors(elementToScore, 5)
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 += re2go.CountCommas(innerText)
// For every 100 characters in this paragraph, add another point. Up to 3 points.
contentScore += int(math.Min(math.Floor(float64(charCount(innerText))/100.0), 3.0))
// Initialize and score ancestors.
ps.forEachNode(ancestors, func(ancestor *html.Node, level int) {
if dom.TagName(ancestor) == "" || ancestor.Parent == nil || ancestor.Parent.Type != html.ElementNode {
return
}
if !ps.hasContentScore(ancestor) {
ps.initializeNode(ancestor)
candidates = append(candidates, ancestor)
}
// Node score divider:
// - parent: 1 (no division)
// - grandparent: 2
// - great grandparent+: ancestor level * 3
var scoreDivider int
switch level {
case 0:
scoreDivider = 1
case 1:
scoreDivider = 2
default:
scoreDivider = level * 3
}
ancestorScore := ps.getContentScore(ancestor)
ancestorScore += float64(contentScore) / float64(scoreDivider)
ps.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 := ps.getContentScore(candidate) * (1 - ps.getLinkDensity(candidate))
ps.logf("candidate %q with score: %f\n", dom.OuterHTML(candidate), candidateScore)
ps.setContentScore(candidate, candidateScore)
}
// After we've 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 ps.getContentScore(candidates[i]) > ps.getContentScore(candidates[j])
})
var topCandidates []*html.Node
if len(candidates) > ps.NTopCandidates {
topCandidates = candidates[:ps.NTopCandidates]
} else {
topCandidates = candidates
}
var topCandidate, parentOfTopCandidate *html.Node
neededToCreateTopCandidate := false
if len(topCandidates) > 0 {
topCandidate = topCandidates[0]
}