2010-04-22 11:55:00 +00:00
|
|
|
#!/usr/bin/env python
|
2015-04-29 14:18:21 +00:00
|
|
|
from __future__ import print_function
|
2010-04-23 11:14:13 +00:00
|
|
|
import logging
|
2010-04-22 11:55:00 +00:00
|
|
|
import re
|
2011-05-03 04:34:29 +00:00
|
|
|
import sys
|
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
from collections import defaultdict
|
|
|
|
from lxml.etree import tostring
|
|
|
|
from lxml.etree import tounicode
|
|
|
|
from lxml.html import document_fromstring
|
|
|
|
from lxml.html import fragment_fromstring
|
|
|
|
|
2015-04-27 09:59:31 +00:00
|
|
|
from .cleaners import clean_attributes
|
|
|
|
from .cleaners import html_cleaner
|
|
|
|
from .htmls import build_doc
|
|
|
|
from .htmls import get_body
|
|
|
|
from .htmls import get_title
|
|
|
|
from .htmls import shorten_title
|
2015-07-26 13:29:50 +00:00
|
|
|
from .compat import str_
|
|
|
|
from .debug import describe, text_content
|
2012-04-17 01:23:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger()
|
|
|
|
|
2011-05-03 04:34:29 +00:00
|
|
|
REGEXES = {
|
2012-04-17 01:23:19 +00:00
|
|
|
'unlikelyCandidatesRe': re.compile('combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup|tweet|twitter', re.I),
|
|
|
|
'okMaybeItsACandidateRe': re.compile('and|article|body|column|main|shadow', re.I),
|
|
|
|
'positiveRe': re.compile('article|body|content|entry|hentry|main|page|pagination|post|text|blog|story', re.I),
|
|
|
|
'negativeRe': re.compile('combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget', re.I),
|
|
|
|
'divToPElementsRe': re.compile('<(a|blockquote|dl|div|img|ol|p|pre|table|ul)', re.I),
|
2012-04-16 21:13:24 +00:00
|
|
|
#'replaceBrsRe': re.compile('(<br[^>]*>[ \n\r\t]*){2,}',re.I),
|
|
|
|
#'replaceFontsRe': re.compile('<(\/?)font[^>]*>',re.I),
|
|
|
|
#'trimRe': re.compile('^\s+|\s+$/'),
|
|
|
|
#'normalizeRe': re.compile('\s{2,}/'),
|
|
|
|
#'killBreaksRe': re.compile('(<br\s*\/?>(\s| ?)*){1,}/'),
|
2015-07-27 05:59:17 +00:00
|
|
|
'videoRe': re.compile('https?:\/\/(www\.)?(youtube|vimeo)\.com', re.I),
|
2012-04-16 21:13:24 +00:00
|
|
|
#skipFootnoteLink: /^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i,
|
2010-04-22 11:55:00 +00:00
|
|
|
}
|
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
|
|
|
|
class Unparseable(ValueError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2011-05-11 12:58:27 +00:00
|
|
|
def to_int(x):
|
2012-04-17 01:23:19 +00:00
|
|
|
if not x:
|
|
|
|
return None
|
2012-04-16 21:13:24 +00:00
|
|
|
x = x.strip()
|
|
|
|
if x.endswith('px'):
|
|
|
|
return int(x[:-2])
|
|
|
|
if x.endswith('em'):
|
|
|
|
return int(x[:-2]) * 12
|
|
|
|
return int(x)
|
2011-05-11 12:58:27 +00:00
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
|
2011-06-01 05:16:32 +00:00
|
|
|
def clean(text):
|
2012-04-16 21:13:24 +00:00
|
|
|
text = re.sub('\s*\n\s*', '\n', text)
|
2015-07-26 13:29:50 +00:00
|
|
|
text = re.sub('\t|[ \t]{2,}', ' ', text)
|
2012-04-16 21:13:24 +00:00
|
|
|
return text.strip()
|
2011-06-01 05:16:32 +00:00
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
|
2011-06-01 05:16:32 +00:00
|
|
|
def text_length(i):
|
2012-04-16 21:13:24 +00:00
|
|
|
return len(clean(i.text_content() or ""))
|
2011-06-01 05:16:32 +00:00
|
|
|
|
2013-10-09 19:39:37 +00:00
|
|
|
regexp_type = type(re.compile('hello, world'))
|
|
|
|
|
|
|
|
def compile_pattern(elements):
|
|
|
|
if not elements:
|
|
|
|
return None
|
2015-04-29 14:18:21 +00:00
|
|
|
elif isinstance(elements, regexp_type):
|
2013-10-09 19:39:37 +00:00
|
|
|
return elements
|
2015-04-29 14:18:21 +00:00
|
|
|
else:
|
|
|
|
# assume string or string like object
|
2013-10-09 19:39:37 +00:00
|
|
|
elements = elements.split(',')
|
2015-04-29 17:33:43 +00:00
|
|
|
return re.compile(u'|'.join([re.escape(x.lower()) for x in elements]), re.U)
|
2010-04-30 14:07:30 +00:00
|
|
|
|
2010-04-22 11:55:00 +00:00
|
|
|
class Document:
|
2012-04-17 01:23:19 +00:00
|
|
|
"""Class to build a etree document out of html."""
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2015-07-26 13:29:50 +00:00
|
|
|
def __init__(self, input, positive_keywords=None, negative_keywords=None,
|
|
|
|
url=None, min_text_length=25, retry_length=250, ):
|
2012-04-17 01:23:19 +00:00
|
|
|
"""Generate the document
|
|
|
|
|
|
|
|
:param input: string of the html content.
|
2015-07-26 13:29:50 +00:00
|
|
|
:param positive_keywords: regex or list of patterns in classes and ids
|
|
|
|
:param negative_keywords: regex or list of patterns in classes and ids
|
|
|
|
:param min_text_length:
|
|
|
|
:param retry_length:
|
|
|
|
|
|
|
|
Example:
|
|
|
|
positive_keywords=["news-item", "block"]
|
|
|
|
negative_keywords=["mysidebar", "related", "ads"]
|
2012-04-17 01:23:19 +00:00
|
|
|
"""
|
2012-04-16 21:13:24 +00:00
|
|
|
self.input = input
|
|
|
|
self.html = None
|
2013-10-09 19:39:37 +00:00
|
|
|
self.encoding = None
|
|
|
|
self.positive_keywords = compile_pattern(positive_keywords)
|
|
|
|
self.negative_keywords = compile_pattern(negative_keywords)
|
2015-07-26 13:29:50 +00:00
|
|
|
self.url = url
|
|
|
|
self.min_text_length = min_text_length
|
|
|
|
self.retry_length = retry_length
|
2012-04-16 21:13:24 +00:00
|
|
|
|
|
|
|
def _html(self, force=False):
|
|
|
|
if force or self.html is None:
|
|
|
|
self.html = self._parse(self.input)
|
|
|
|
return self.html
|
|
|
|
|
|
|
|
def _parse(self, input):
|
2013-10-09 19:39:37 +00:00
|
|
|
doc, self.encoding = build_doc(input)
|
2012-04-16 21:13:24 +00:00
|
|
|
doc = html_cleaner.clean_html(doc)
|
2015-07-26 13:29:50 +00:00
|
|
|
base_href = self.url
|
2012-04-16 21:13:24 +00:00
|
|
|
if base_href:
|
2015-07-27 04:06:28 +00:00
|
|
|
# trying to guard against bad links like <a href="http://[http://...">
|
|
|
|
try:
|
|
|
|
# such support is added in lxml 3.3.0
|
|
|
|
doc.make_links_absolute(base_href, resolve_base_href=True, handle_failures='discard')
|
|
|
|
except TypeError: #make_links_absolute() got an unexpected keyword argument 'handle_failures'
|
|
|
|
# then we have lxml < 3.3.0
|
|
|
|
# please upgrade to lxml >= 3.3.0 if you're failing here!
|
|
|
|
doc.make_links_absolute(base_href, resolve_base_href=True)
|
2012-04-16 21:13:24 +00:00
|
|
|
else:
|
|
|
|
doc.resolve_base_href()
|
|
|
|
return doc
|
|
|
|
|
|
|
|
def content(self):
|
|
|
|
return get_body(self._html(True))
|
|
|
|
|
|
|
|
def title(self):
|
|
|
|
return get_title(self._html(True))
|
|
|
|
|
|
|
|
def short_title(self):
|
|
|
|
return shorten_title(self._html(True))
|
|
|
|
|
2012-09-13 15:09:14 +00:00
|
|
|
def get_clean_html(self):
|
|
|
|
return clean_attributes(tounicode(self.html))
|
|
|
|
|
2012-04-17 14:17:14 +00:00
|
|
|
def summary(self, html_partial=False):
|
2012-04-17 01:23:19 +00:00
|
|
|
"""Generate the summary of the html docuemnt
|
|
|
|
|
2012-04-17 14:17:14 +00:00
|
|
|
:param html_partial: return only the div of the document, don't wrap
|
2012-04-17 01:23:19 +00:00
|
|
|
in html and body tags.
|
|
|
|
|
|
|
|
"""
|
2012-04-16 21:13:24 +00:00
|
|
|
try:
|
|
|
|
ruthless = True
|
|
|
|
while True:
|
|
|
|
self._html(True)
|
|
|
|
for i in self.tags(self.html, 'script', 'style'):
|
|
|
|
i.drop_tree()
|
|
|
|
for i in self.tags(self.html, 'body'):
|
|
|
|
i.set('id', 'readabilityBody')
|
|
|
|
if ruthless:
|
|
|
|
self.remove_unlikely_candidates()
|
|
|
|
self.transform_misused_divs_into_paragraphs()
|
|
|
|
candidates = self.score_paragraphs()
|
|
|
|
|
|
|
|
best_candidate = self.select_best_candidate(candidates)
|
|
|
|
|
|
|
|
if best_candidate:
|
2012-04-17 00:55:13 +00:00
|
|
|
article = self.get_article(candidates, best_candidate,
|
2012-04-17 14:17:14 +00:00
|
|
|
html_partial=html_partial)
|
2012-04-16 21:13:24 +00:00
|
|
|
else:
|
|
|
|
if ruthless:
|
2015-07-26 13:29:50 +00:00
|
|
|
log.info("ruthless removal did not work. ")
|
2012-04-16 21:13:24 +00:00
|
|
|
ruthless = False
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug(
|
2012-04-17 01:23:19 +00:00
|
|
|
("ended up stripping too much - "
|
|
|
|
"going for a safer _parse"))
|
2012-04-16 21:13:24 +00:00
|
|
|
# try again
|
|
|
|
continue
|
|
|
|
else:
|
2012-04-17 01:23:19 +00:00
|
|
|
log.debug(
|
|
|
|
("Ruthless and lenient parsing did not work. "
|
|
|
|
"Returning raw html"))
|
2012-04-16 21:13:24 +00:00
|
|
|
article = self.html.find('body')
|
|
|
|
if article is None:
|
|
|
|
article = self.html
|
|
|
|
cleaned_article = self.sanitize(article, candidates)
|
2014-02-07 20:27:15 +00:00
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
article_length = len(cleaned_article or '')
|
2015-07-26 13:29:50 +00:00
|
|
|
retry_length = self.retry_length
|
2012-04-17 01:23:19 +00:00
|
|
|
of_acceptable_length = article_length >= retry_length
|
2012-04-16 21:13:24 +00:00
|
|
|
if ruthless and not of_acceptable_length:
|
|
|
|
ruthless = False
|
2012-04-17 01:23:19 +00:00
|
|
|
# Loop through and try again.
|
|
|
|
continue
|
2012-04-16 21:13:24 +00:00
|
|
|
else:
|
|
|
|
return cleaned_article
|
2015-04-29 14:18:21 +00:00
|
|
|
except Exception as e:
|
2012-04-17 01:23:19 +00:00
|
|
|
log.exception('error getting summary: ')
|
2015-04-29 14:18:21 +00:00
|
|
|
if sys.version_info[0] == 2:
|
2015-04-29 21:35:18 +00:00
|
|
|
from .compat.two import raise_with_traceback
|
2015-04-29 14:18:21 +00:00
|
|
|
else:
|
2015-04-29 21:35:18 +00:00
|
|
|
from .compat.three import raise_with_traceback
|
2015-07-26 13:29:50 +00:00
|
|
|
raise_with_traceback(Unparseable, sys.exc_info()[2], str_(e))
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2012-04-17 14:17:14 +00:00
|
|
|
def get_article(self, candidates, best_candidate, html_partial=False):
|
2012-04-17 01:23:19 +00:00
|
|
|
# Now that we have the top candidate, look through its siblings for
|
|
|
|
# content that might also be related.
|
2012-04-16 21:13:24 +00:00
|
|
|
# Things like preambles, content split by ads that we removed, etc.
|
2012-04-17 01:23:19 +00:00
|
|
|
sibling_score_threshold = max([
|
|
|
|
10,
|
|
|
|
best_candidate['content_score'] * 0.2])
|
2012-04-17 00:55:13 +00:00
|
|
|
# create a new html document with a html->body->div
|
2012-04-17 14:17:14 +00:00
|
|
|
if html_partial:
|
2012-04-17 00:55:13 +00:00
|
|
|
output = fragment_fromstring('<div/>')
|
|
|
|
else:
|
|
|
|
output = document_fromstring('<div/>')
|
2012-04-16 21:13:24 +00:00
|
|
|
best_elem = best_candidate['elem']
|
2015-05-06 07:34:55 +00:00
|
|
|
parent = best_elem.getparent()
|
2015-05-06 08:33:14 +00:00
|
|
|
siblings = parent.getchildren() if parent is not None else [best_elem]
|
2015-05-06 07:34:55 +00:00
|
|
|
for sibling in siblings:
|
2012-04-17 01:23:19 +00:00
|
|
|
# in lxml there no concept of simple text
|
|
|
|
# if isinstance(sibling, NavigableString): continue
|
2012-04-16 21:13:24 +00:00
|
|
|
append = False
|
|
|
|
if sibling is best_elem:
|
|
|
|
append = True
|
2012-04-17 01:23:19 +00:00
|
|
|
sibling_key = sibling # HashableElement(sibling)
|
|
|
|
if sibling_key in candidates and \
|
|
|
|
candidates[sibling_key]['content_score'] >= sibling_score_threshold:
|
2012-04-16 21:13:24 +00:00
|
|
|
append = True
|
|
|
|
|
|
|
|
if sibling.tag == "p":
|
|
|
|
link_density = self.get_link_density(sibling)
|
|
|
|
node_content = sibling.text or ""
|
|
|
|
node_length = len(node_content)
|
|
|
|
|
|
|
|
if node_length > 80 and link_density < 0.25:
|
|
|
|
append = True
|
2012-04-17 01:23:19 +00:00
|
|
|
elif node_length <= 80 \
|
|
|
|
and link_density == 0 \
|
|
|
|
and re.search('\.( |$)', node_content):
|
2012-04-16 21:13:24 +00:00
|
|
|
append = True
|
|
|
|
|
|
|
|
if append:
|
2012-04-17 00:55:13 +00:00
|
|
|
# We don't want to append directly to output, but the div
|
|
|
|
# in html->body->div
|
2012-04-17 14:17:14 +00:00
|
|
|
if html_partial:
|
2012-04-17 00:55:13 +00:00
|
|
|
output.append(sibling)
|
|
|
|
else:
|
|
|
|
output.getchildren()[0].getchildren()[0].append(sibling)
|
2012-04-16 21:13:24 +00:00
|
|
|
#if output is not None:
|
|
|
|
# output.append(best_elem)
|
|
|
|
return output
|
|
|
|
|
|
|
|
def select_best_candidate(self, candidates):
|
2015-07-26 13:29:50 +00:00
|
|
|
if not candidates:
|
|
|
|
return None
|
|
|
|
|
|
|
|
sorted_candidates = sorted(
|
|
|
|
candidates.values(),
|
|
|
|
key=lambda x: x['content_score'],
|
|
|
|
reverse=True
|
|
|
|
)
|
2012-04-16 21:13:24 +00:00
|
|
|
for candidate in sorted_candidates[:5]:
|
|
|
|
elem = candidate['elem']
|
2015-07-26 13:29:50 +00:00
|
|
|
log.info("Top 5 : %6.3f %s" % (
|
2012-04-17 01:23:19 +00:00
|
|
|
candidate['content_score'],
|
|
|
|
describe(elem)))
|
2012-04-16 21:13:24 +00:00
|
|
|
|
|
|
|
best_candidate = sorted_candidates[0]
|
|
|
|
return best_candidate
|
|
|
|
|
|
|
|
def get_link_density(self, elem):
|
|
|
|
link_length = 0
|
|
|
|
for i in elem.findall(".//a"):
|
|
|
|
link_length += text_length(i)
|
|
|
|
#if len(elem.findall(".//div") or elem.findall(".//p")):
|
|
|
|
# link_length = link_length
|
|
|
|
total_length = text_length(elem)
|
|
|
|
return float(link_length) / max(total_length, 1)
|
|
|
|
|
|
|
|
def score_paragraphs(self, ):
|
2015-07-26 13:29:50 +00:00
|
|
|
MIN_LEN = self.min_text_length
|
2012-04-16 21:13:24 +00:00
|
|
|
candidates = {}
|
|
|
|
ordered = []
|
|
|
|
for elem in self.tags(self._html(), "p", "pre", "td"):
|
|
|
|
parent_node = elem.getparent()
|
|
|
|
if parent_node is None:
|
|
|
|
continue
|
|
|
|
grand_parent_node = parent_node.getparent()
|
|
|
|
|
|
|
|
inner_text = clean(elem.text_content() or "")
|
|
|
|
inner_text_len = len(inner_text)
|
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
# If this paragraph is less than 25 characters
|
|
|
|
# don't even count it.
|
2012-04-16 21:13:24 +00:00
|
|
|
if inner_text_len < MIN_LEN:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if parent_node not in candidates:
|
|
|
|
candidates[parent_node] = self.score_node(parent_node)
|
|
|
|
ordered.append(parent_node)
|
|
|
|
|
|
|
|
if grand_parent_node is not None and grand_parent_node not in candidates:
|
2012-04-17 01:23:19 +00:00
|
|
|
candidates[grand_parent_node] = self.score_node(
|
|
|
|
grand_parent_node)
|
2012-04-16 21:13:24 +00:00
|
|
|
ordered.append(grand_parent_node)
|
|
|
|
|
|
|
|
content_score = 1
|
|
|
|
content_score += len(inner_text.split(','))
|
|
|
|
content_score += min((inner_text_len / 100), 3)
|
|
|
|
#if elem not in candidates:
|
|
|
|
# candidates[elem] = self.score_node(elem)
|
|
|
|
|
|
|
|
#WTF? candidates[elem]['content_score'] += content_score
|
|
|
|
candidates[parent_node]['content_score'] += content_score
|
|
|
|
if grand_parent_node is not None:
|
|
|
|
candidates[grand_parent_node]['content_score'] += content_score / 2.0
|
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
# 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.
|
2012-04-16 21:13:24 +00:00
|
|
|
for elem in ordered:
|
|
|
|
candidate = candidates[elem]
|
|
|
|
ld = self.get_link_density(elem)
|
|
|
|
score = candidate['content_score']
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug("Branch %6.3f %s link density %.3f -> %6.3f" % (
|
2012-04-17 01:23:19 +00:00
|
|
|
score,
|
|
|
|
describe(elem),
|
|
|
|
ld,
|
|
|
|
score * (1 - ld)))
|
2012-04-16 21:13:24 +00:00
|
|
|
candidate['content_score'] *= (1 - ld)
|
|
|
|
|
|
|
|
return candidates
|
|
|
|
|
|
|
|
def class_weight(self, e):
|
|
|
|
weight = 0
|
2013-10-09 19:39:37 +00:00
|
|
|
for feature in [e.get('class', None), e.get('id', None)]:
|
|
|
|
if feature:
|
|
|
|
if REGEXES['negativeRe'].search(feature):
|
|
|
|
weight -= 25
|
|
|
|
|
|
|
|
if REGEXES['positiveRe'].search(feature):
|
|
|
|
weight += 25
|
|
|
|
|
|
|
|
if self.positive_keywords and self.positive_keywords.search(feature):
|
|
|
|
weight += 25
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2013-10-09 19:39:37 +00:00
|
|
|
if self.negative_keywords and self.negative_keywords.search(feature):
|
|
|
|
weight -= 25
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2013-10-09 19:39:37 +00:00
|
|
|
if self.positive_keywords and self.positive_keywords.match('tag-'+e.tag):
|
|
|
|
weight += 25
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2013-10-09 19:39:37 +00:00
|
|
|
if self.negative_keywords and self.negative_keywords.match('tag-'+e.tag):
|
|
|
|
weight -= 25
|
2012-04-16 21:13:24 +00:00
|
|
|
|
|
|
|
return weight
|
|
|
|
|
|
|
|
def score_node(self, elem):
|
|
|
|
content_score = self.class_weight(elem)
|
|
|
|
name = elem.tag.lower()
|
|
|
|
if name == "div":
|
|
|
|
content_score += 5
|
|
|
|
elif name in ["pre", "td", "blockquote"]:
|
|
|
|
content_score += 3
|
|
|
|
elif name in ["address", "ol", "ul", "dl", "dd", "dt", "li", "form"]:
|
|
|
|
content_score -= 3
|
|
|
|
elif name in ["h1", "h2", "h3", "h4", "h5", "h6", "th"]:
|
|
|
|
content_score -= 5
|
|
|
|
return {
|
|
|
|
'content_score': content_score,
|
|
|
|
'elem': elem
|
|
|
|
}
|
|
|
|
|
|
|
|
def remove_unlikely_candidates(self):
|
|
|
|
for elem in self.html.iter():
|
|
|
|
s = "%s %s" % (elem.get('class', ''), elem.get('id', ''))
|
|
|
|
if len(s) < 2:
|
|
|
|
continue
|
2012-04-17 15:04:36 +00:00
|
|
|
if REGEXES['unlikelyCandidatesRe'].search(s) and (not REGEXES['okMaybeItsACandidateRe'].search(s)) and elem.tag not in ['html', 'body']:
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug("Removing unlikely candidate - %s" % describe(elem))
|
2012-04-16 21:13:24 +00:00
|
|
|
elem.drop_tree()
|
|
|
|
|
|
|
|
def transform_misused_divs_into_paragraphs(self):
|
|
|
|
for elem in self.tags(self.html, 'div'):
|
2012-04-17 01:23:19 +00:00
|
|
|
# transform <div>s that do not contain other block elements into
|
|
|
|
# <p>s
|
|
|
|
#FIXME: The current implementation ignores all descendants that
|
|
|
|
# are not direct children of elem
|
|
|
|
# This results in incorrect results in case there is an <img>
|
|
|
|
# buried within an <a> for example
|
|
|
|
if not REGEXES['divToPElementsRe'].search(
|
2015-07-26 13:29:50 +00:00
|
|
|
str_(b''.join(map(tostring, list(elem))))):
|
|
|
|
#log.debug("Altering %s to p" % (describe(elem)))
|
2012-04-16 21:13:24 +00:00
|
|
|
elem.tag = "p"
|
|
|
|
#print "Fixed element "+describe(elem)
|
|
|
|
|
|
|
|
for elem in self.tags(self.html, 'div'):
|
|
|
|
if elem.text and elem.text.strip():
|
|
|
|
p = fragment_fromstring('<p/>')
|
|
|
|
p.text = elem.text
|
|
|
|
elem.text = None
|
|
|
|
elem.insert(0, p)
|
|
|
|
#print "Appended "+tounicode(p)+" to "+describe(elem)
|
|
|
|
|
|
|
|
for pos, child in reversed(list(enumerate(elem))):
|
|
|
|
if child.tail and child.tail.strip():
|
|
|
|
p = fragment_fromstring('<p/>')
|
|
|
|
p.text = child.tail
|
|
|
|
child.tail = None
|
|
|
|
elem.insert(pos + 1, p)
|
|
|
|
#print "Inserted "+tounicode(p)+" to "+describe(elem)
|
|
|
|
if child.tag == 'br':
|
|
|
|
#print 'Dropped <br> at '+describe(elem)
|
|
|
|
child.drop_tree()
|
|
|
|
|
|
|
|
def tags(self, node, *tag_names):
|
|
|
|
for tag_name in tag_names:
|
|
|
|
for e in node.findall('.//%s' % tag_name):
|
|
|
|
yield e
|
|
|
|
|
|
|
|
def reverse_tags(self, node, *tag_names):
|
|
|
|
for tag_name in tag_names:
|
|
|
|
for e in reversed(node.findall('.//%s' % tag_name)):
|
|
|
|
yield e
|
|
|
|
|
|
|
|
def sanitize(self, node, candidates):
|
2015-07-26 13:29:50 +00:00
|
|
|
MIN_LEN = self.min_text_length
|
2012-04-16 21:13:24 +00:00
|
|
|
for header in self.tags(node, "h1", "h2", "h3", "h4", "h5", "h6"):
|
|
|
|
if self.class_weight(header) < 0 or self.get_link_density(header) > 0.33:
|
|
|
|
header.drop_tree()
|
|
|
|
|
2014-02-07 20:04:15 +00:00
|
|
|
for elem in self.tags(node, "form", "textarea"):
|
2012-04-16 21:13:24 +00:00
|
|
|
elem.drop_tree()
|
2014-02-07 20:04:15 +00:00
|
|
|
|
|
|
|
for elem in self.tags(node, "iframe"):
|
2014-02-07 20:27:15 +00:00
|
|
|
if "src" in elem.attrib and REGEXES["videoRe"].search(elem.attrib["src"]):
|
|
|
|
elem.text = "VIDEO" # ADD content to iframe text node to force <iframe></iframe> proper output
|
|
|
|
else:
|
2014-02-07 20:04:15 +00:00
|
|
|
elem.drop_tree()
|
|
|
|
|
2012-04-16 21:13:24 +00:00
|
|
|
allowed = {}
|
|
|
|
# Conditionally clean <table>s, <ul>s, and <div>s
|
|
|
|
for el in self.reverse_tags(node, "table", "ul", "div"):
|
|
|
|
if el in allowed:
|
|
|
|
continue
|
|
|
|
weight = self.class_weight(el)
|
|
|
|
if el in candidates:
|
|
|
|
content_score = candidates[el]['content_score']
|
|
|
|
#print '!',el, '-> %6.3f' % content_score
|
|
|
|
else:
|
|
|
|
content_score = 0
|
|
|
|
tag = el.tag
|
|
|
|
|
|
|
|
if weight + content_score < 0:
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug("Removed %s with score %6.3f and weight %-3s" %
|
2012-04-16 21:13:24 +00:00
|
|
|
(describe(el), content_score, weight, ))
|
|
|
|
el.drop_tree()
|
|
|
|
elif el.text_content().count(",") < 10:
|
|
|
|
counts = {}
|
|
|
|
for kind in ['p', 'img', 'li', 'a', 'embed', 'input']:
|
2012-04-17 01:23:19 +00:00
|
|
|
counts[kind] = len(el.findall('.//%s' % kind))
|
2012-04-16 21:13:24 +00:00
|
|
|
counts["li"] -= 100
|
2014-09-22 08:31:31 +00:00
|
|
|
counts["input"] -= len(el.findall('.//input[@type="hidden"]'))
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2012-04-17 01:23:19 +00:00
|
|
|
# Count the text length excluding any surrounding whitespace
|
|
|
|
content_length = text_length(el)
|
2012-04-16 21:13:24 +00:00
|
|
|
link_density = self.get_link_density(el)
|
|
|
|
parent_node = el.getparent()
|
|
|
|
if parent_node is not None:
|
|
|
|
if parent_node in candidates:
|
|
|
|
content_score = candidates[parent_node]['content_score']
|
|
|
|
else:
|
|
|
|
content_score = 0
|
|
|
|
#if parent_node is not None:
|
|
|
|
#pweight = self.class_weight(parent_node) + content_score
|
|
|
|
#pname = describe(parent_node)
|
|
|
|
#else:
|
|
|
|
#pweight = 0
|
|
|
|
#pname = "no parent"
|
|
|
|
to_remove = False
|
|
|
|
reason = ""
|
|
|
|
|
|
|
|
#if el.tag == 'div' and counts["img"] >= 1:
|
|
|
|
# continue
|
2015-04-27 08:35:00 +00:00
|
|
|
if counts["p"] and counts["img"] > 1+counts["p"]*1.3:
|
2012-04-16 21:13:24 +00:00
|
|
|
reason = "too many images (%s)" % counts["img"]
|
|
|
|
to_remove = True
|
|
|
|
elif counts["li"] > counts["p"] and tag != "ul" and tag != "ol":
|
|
|
|
reason = "more <li>s than <p>s"
|
|
|
|
to_remove = True
|
|
|
|
elif counts["input"] > (counts["p"] / 3):
|
|
|
|
reason = "less than 3x <p>s than <input>s"
|
|
|
|
to_remove = True
|
2015-07-26 13:29:50 +00:00
|
|
|
elif content_length < MIN_LEN and counts["img"] == 0:
|
2012-04-16 21:13:24 +00:00
|
|
|
reason = "too short content length %s without a single image" % content_length
|
|
|
|
to_remove = True
|
2015-07-26 13:29:50 +00:00
|
|
|
elif content_length < MIN_LEN and counts["img"] > 2:
|
|
|
|
reason = "too short content length %s and too many images" % content_length
|
|
|
|
to_remove = True
|
2012-04-16 21:13:24 +00:00
|
|
|
elif weight < 25 and link_density > 0.2:
|
2012-04-17 01:23:19 +00:00
|
|
|
reason = "too many links %.3f for its weight %s" % (
|
|
|
|
link_density, weight)
|
2012-04-16 21:13:24 +00:00
|
|
|
to_remove = True
|
|
|
|
elif weight >= 25 and link_density > 0.5:
|
2012-04-17 01:23:19 +00:00
|
|
|
reason = "too many links %.3f for its weight %s" % (
|
|
|
|
link_density, weight)
|
2012-04-16 21:13:24 +00:00
|
|
|
to_remove = True
|
|
|
|
elif (counts["embed"] == 1 and content_length < 75) or counts["embed"] > 1:
|
|
|
|
reason = "<embed>s with too short content length, or too many <embed>s"
|
|
|
|
to_remove = True
|
2015-07-26 13:29:50 +00:00
|
|
|
elif not content_length:
|
|
|
|
reason = "no content"
|
|
|
|
to_remove = True
|
2012-04-16 21:13:24 +00:00
|
|
|
# if el.tag == 'div' and counts['img'] >= 1 and to_remove:
|
|
|
|
# imgs = el.findall('.//img')
|
|
|
|
# valid_img = False
|
2015-07-26 13:29:50 +00:00
|
|
|
# log.debug(tounicode(el))
|
2012-04-16 21:13:24 +00:00
|
|
|
# for img in imgs:
|
2011-06-01 05:16:32 +00:00
|
|
|
#
|
2012-04-16 21:13:24 +00:00
|
|
|
# height = img.get('height')
|
|
|
|
# text_length = img.get('text_length')
|
2015-07-26 13:29:50 +00:00
|
|
|
# log.debug ("height %s text_length %s" %(repr(height), repr(text_length)))
|
2012-04-16 21:13:24 +00:00
|
|
|
# if to_int(height) >= 100 or to_int(text_length) >= 100:
|
|
|
|
# valid_img = True
|
2015-07-26 13:29:50 +00:00
|
|
|
# log.debug("valid image" + tounicode(img))
|
2012-04-16 21:13:24 +00:00
|
|
|
# break
|
|
|
|
# if valid_img:
|
|
|
|
# to_remove = False
|
2015-07-26 13:29:50 +00:00
|
|
|
# log.debug("Allowing %s" %el.text_content())
|
2012-04-16 21:13:24 +00:00
|
|
|
# for desnode in self.tags(el, "table", "ul", "div"):
|
|
|
|
# allowed[desnode] = True
|
|
|
|
|
|
|
|
#find x non empty preceding and succeeding siblings
|
|
|
|
i, j = 0, 0
|
2012-04-17 01:23:19 +00:00
|
|
|
x = 1
|
2012-04-16 21:13:24 +00:00
|
|
|
siblings = []
|
|
|
|
for sib in el.itersiblings():
|
2015-07-26 13:29:50 +00:00
|
|
|
#log.debug(sib.text_content())
|
2012-04-16 21:13:24 +00:00
|
|
|
sib_content_length = text_length(sib)
|
|
|
|
if sib_content_length:
|
|
|
|
i =+ 1
|
|
|
|
siblings.append(sib_content_length)
|
|
|
|
if i == x:
|
|
|
|
break
|
|
|
|
for sib in el.itersiblings(preceding=True):
|
2015-07-26 13:29:50 +00:00
|
|
|
#log.debug(sib.text_content())
|
2012-04-16 21:13:24 +00:00
|
|
|
sib_content_length = text_length(sib)
|
|
|
|
if sib_content_length:
|
|
|
|
j =+ 1
|
|
|
|
siblings.append(sib_content_length)
|
|
|
|
if j == x:
|
|
|
|
break
|
2015-07-26 13:29:50 +00:00
|
|
|
#log.debug(str_(siblings))
|
2012-04-17 01:23:19 +00:00
|
|
|
if siblings and sum(siblings) > 1000:
|
2012-04-16 21:13:24 +00:00
|
|
|
to_remove = False
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug("Allowing %s" % describe(el))
|
2012-04-16 21:13:24 +00:00
|
|
|
for desnode in self.tags(el, "table", "ul", "div"):
|
|
|
|
allowed[desnode] = True
|
|
|
|
|
|
|
|
if to_remove:
|
2015-07-26 13:29:50 +00:00
|
|
|
log.debug("Removed %6.3f %s with weight %s cause it has %s." %
|
2012-04-16 21:13:24 +00:00
|
|
|
(content_score, describe(el), weight, reason))
|
|
|
|
#print tounicode(el)
|
2015-07-26 13:29:50 +00:00
|
|
|
#log.debug("pname %s pweight %.3f" %(pname, pweight))
|
2012-04-16 21:13:24 +00:00
|
|
|
el.drop_tree()
|
2015-07-26 13:29:50 +00:00
|
|
|
else:
|
|
|
|
log.debug("Not removing %s of length %s: %s" % (
|
|
|
|
describe(el), content_length, text_content(el)))
|
2012-04-17 00:55:13 +00:00
|
|
|
|
2012-09-13 15:09:14 +00:00
|
|
|
self.html = node
|
|
|
|
return self.get_clean_html()
|
2012-04-16 21:13:24 +00:00
|
|
|
|
2010-04-22 11:55:00 +00:00
|
|
|
|
|
|
|
def main():
|
2015-07-26 13:29:50 +00:00
|
|
|
VERBOSITY = {
|
|
|
|
1: logging.WARNING,
|
|
|
|
2: logging.INFO,
|
|
|
|
3: logging.DEBUG
|
|
|
|
}
|
2015-06-24 14:21:04 +00:00
|
|
|
|
2012-04-16 21:13:24 +00:00
|
|
|
from optparse import OptionParser
|
|
|
|
parser = OptionParser(usage="%prog: [options] [file]")
|
2015-07-26 13:29:50 +00:00
|
|
|
parser.add_option('-v', '--verbose', action='count', default=0)
|
|
|
|
parser.add_option('-b', '--browser', default=None, action='store_true', help="open in browser")
|
|
|
|
parser.add_option('-l', '--log', default=None, help="save logs into file (appended)")
|
2012-04-17 01:23:19 +00:00
|
|
|
parser.add_option('-u', '--url', default=None, help="use URL instead of a local file")
|
2015-07-26 13:29:50 +00:00
|
|
|
parser.add_option('-x', '--xpath', default=None, help="add original xpath")
|
2013-10-09 19:39:37 +00:00
|
|
|
parser.add_option('-p', '--positive-keywords', default=None, help="positive keywords (separated with comma)", action='store')
|
|
|
|
parser.add_option('-n', '--negative-keywords', default=None, help="negative keywords (separated with comma)", action='store')
|
2012-04-16 21:13:24 +00:00
|
|
|
(options, args) = parser.parse_args()
|
|
|
|
|
2015-07-26 13:29:50 +00:00
|
|
|
if options.verbose:
|
|
|
|
logging.basicConfig(level=VERBOSITY[options.verbose], filename=options.log,
|
|
|
|
format='%(asctime)s: %(levelname)s: %(message)s (at %(filename)s: %(lineno)d)')
|
|
|
|
|
2012-04-16 21:13:24 +00:00
|
|
|
if not (len(args) == 1 or options.url):
|
|
|
|
parser.print_help()
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
file = None
|
|
|
|
if options.url:
|
2015-07-26 13:29:50 +00:00
|
|
|
if sys.version_info[0] == 3:
|
|
|
|
import urllib.request, urllib.parse, urllib.error
|
|
|
|
file = urllib.request.urlopen(options.url)
|
|
|
|
else:
|
|
|
|
import urllib2
|
|
|
|
file = urllib2.urlopen(options.url)
|
2012-04-16 21:13:24 +00:00
|
|
|
else:
|
|
|
|
file = open(args[0], 'rt')
|
|
|
|
try:
|
2015-07-26 13:29:50 +00:00
|
|
|
doc = Document(file.read(),
|
2013-10-09 19:39:37 +00:00
|
|
|
url=options.url,
|
|
|
|
positive_keywords = options.positive_keywords,
|
|
|
|
negative_keywords = options.negative_keywords,
|
2015-07-26 13:29:50 +00:00
|
|
|
)
|
|
|
|
if options.browser:
|
|
|
|
from .browser import open_in_browser
|
|
|
|
result = '<h2>' + doc.short_title() + '</h2><br/>' + doc.summary()
|
|
|
|
open_in_browser(result)
|
|
|
|
else:
|
|
|
|
enc = sys.__stdout__.encoding or 'utf-8' # XXX: this hack could not always work, better to set PYTHONIOENCODING
|
|
|
|
result = 'Title:' + doc.short_title() + '\n' + doc.summary()
|
|
|
|
if sys.version_info[0] == 3:
|
|
|
|
print(result)
|
|
|
|
else:
|
|
|
|
print(result.encode(enc, 'replace'))
|
2012-04-16 21:13:24 +00:00
|
|
|
finally:
|
|
|
|
file.close()
|
2010-04-22 11:55:00 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2012-04-16 21:13:24 +00:00
|
|
|
main()
|