desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Set input_selector with field_container_selector.'
| def __init__(self, case, inline_number, inline_related_name=None, **kwargs):
| super(InlineSelectOptionMultiple, self).__init__(case, inline_number, inline_related_name=inline_related_name, **kwargs)
self.input_selector = (u'%s %s' % (self.field_container_selector, self.input_selector))
|
'Forward type. Should be implemented in subclasses.'
| @property
def type(self):
| raise NotImplementedError('Please use one of my subclasses')
|
'Convert to dictionary which will be rendered as JSON.'
| def to_dict(self):
| return {'type': self.type}
|
'Instantiate a forwarded field value.'
| def __init__(self, src, dst=None):
| self.src = src
self.dst = dst
|
'Convert to dictionary which will be rendered as JSON.'
| def to_dict(self):
| d = super(Field, self).to_dict()
d.update(src=self.src)
if (self.dst is not None):
d.update(dst=self.dst)
return d
|
'Instantiate a forwarded constant value.'
| def __init__(self, val, dst):
| self.val = val
self.dst = dst
|
'Convert to dictionary which will be rendered as JSON.'
| def to_dict(self):
| d = super(Const, self).to_dict()
d.update(val=self.val)
d.update(dst=self.dst)
return d
|
'Override that uses a form field\'s ``value_from_object()``.'
| def __init__(self, *args, **kwargs):
| super(FutureModelForm, self).__init__(*args, **kwargs)
for (name, field) in self.fields.items():
if (not hasattr(field, 'value_from_object')):
continue
self.initial[name] = field.value_from_object(self.instance, name)
|
'Override that uses the form field\'s ``save_object_data()``.'
| def _post_clean(self):
| super(FutureModelForm, self)._post_clean()
for (name, field) in self.fields.items():
if (not hasattr(field, 'save_object_data')):
continue
field.save_object_data(self.instance, name, self.cleaned_data.get(name, None))
|
'Override that uses the form field\'s ``save_object_data()``.'
| def _save_m2m(self):
| cleaned_data = self.cleaned_data
exclude = self._meta.exclude
fields = self._meta.fields
opts = self.instance._meta
handled = []
for (name, field) in self.fields.items():
if (not hasattr(field, 'save_relation_data')):
continue
field.save_relation_data(self.instance, n... |
'Backport from Django 1.9+ for 1.8.'
| def save(self, commit=True):
| if self.errors:
raise ValueError(("The %s could not be %s because the data didn't validate." % (self.instance._meta.object_name, ('created' if self.instance._state.adding else 'changed'))))
if commit:
self.instance.save()
self._save_m2m()
else:
s... |
'Set :py:attr:`forwarded` and :py:attr:`q`.'
| def dispatch(self, request, *args, **kwargs):
| if (request.method.upper() not in self.http_method_allowed):
return HttpResponseNotAllowed(self.http_method_allowed)
try:
self.forwarded = json.loads(getattr(request, request.method).get('forward', '{}'))
except ValueError:
return HttpResponseBadRequest('Invalid JSON data')
... |
'For widgets that have infinite-scroll feature.'
| def has_more(self, context):
| return context['page_obj'].has_next()
|
'Return the value of a result.'
| def get_result_value(self, result):
| return str(result.pk)
|
'Return the label of a result.'
| def get_result_label(self, result):
| return six.text_type(result)
|
'Filter the queryset with GET[\'q\'].'
| def get_queryset(self):
| qs = super(BaseQuerySetView, self).get_queryset()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
|
'Create an object given a text.'
| def create_object(self, text):
| return self.get_queryset().create(**{self.create_field: text})
|
'Return True if the user has the permission to add a model.'
| def has_add_permission(self, request):
| if (not request.user.is_authenticated()):
return False
opts = self.get_queryset().model._meta
codename = get_permission_codename('add', opts)
return request.user.has_perm(('%s.%s' % (opts.app_label, codename)))
|
'Create an object given a text after checking permissions.'
| def post(self, request):
| if (not self.has_add_permission(request)):
return http.HttpResponseForbidden()
if (not self.create_field):
raise ImproperlyConfigured('Missing "create_field"')
text = request.POST.get('text', None)
if (text is None):
return http.HttpResponseBadRequest()
result = self.creat... |
'Return the QuerySet from the QuerySetSequence for a ctype.'
| def get_queryset_for_content_type(self, content_type_id):
| content_type = ContentType.objects.get_for_id(content_type_id)
for queryset in self.queryset.query._querysets:
if (queryset.model.__name__ == 'QuerySequenceModel'):
model = queryset.model.__bases__[0]
else:
model = queryset.model
if (model == content_type.model_cl... |
'Raise a ValidationError for invalid_choice.
The validation error left unprecise about the exact error for security
reasons, to prevent an attacker doing information gathering to reverse
valid content type and object ids.'
| def raise_invalid_choice(self, params=None):
| raise forms.ValidationError(self.error_messages['invalid_choice'], code='invalid_choice', params=params)
|
'Return a tuple of ctype id, object id for value.'
| def get_content_type_id_object_id(self, value):
| return value.split('-', 1)
|
'Given a string like \'3-5\', return the model of ctype #3 and pk 5.
Note that in the case of ModelChoiceField, to_python is also in charge
of security, it\'s important to get the results from self.queryset.'
| def to_python(self, value):
| if (not value):
return value
(content_type_id, object_id) = self.get_content_type_id_object_id(value)
queryset = self.get_queryset_for_content_type(content_type_id)
if (queryset is None):
self.raise_invalid_choice()
try:
return queryset.get(pk=object_id)
except queryset.m... |
'Overwrite self.choices to exclude unselected values.'
| def filter_choices_to_render(self, selected_choices):
| if ((len(selected_choices) == 1) and (not selected_choices[0])):
selected_choices = []
ctype_models = {}
for choice in selected_choices:
(ctype_pk, model_pk) = choice.split('-')
ctype_pk = int(ctype_pk)
ctype_models.setdefault(ctype_pk, [])
ctype_models[ctype_pk].appe... |
'Don\'t paginate if :py:attr:`mixup`.'
| def get_paginate_by(self, queryset):
| return (self.paginate_by if (not self.mixup) else None)
|
'Return False if :py:attr:`mixup`.'
| def has_more(self, context):
| if self.mixup:
return False
return super(BaseQuerySetSequenceView, self).has_more(context)
|
'Return a queryset with different model types.'
| def mixup_querysets(self, qs):
| if len(list(qs.query._querysets)):
limit = int((self.paginate_by / len(qs.query._querysets)))
qs.query._querysets[0][:2]
qs = QuerySetSequence(*[q[:limit] for q in qs.query._querysets])
return qs
|
'Mix results from all querysets in QuerySetSequence if self.mixup.'
| def get_queryset(self):
| qs = super(BaseQuerySetSequenceView, self).get_queryset()
if self.mixup:
qs = self.mixup_querysets(qs)
return qs
|
'Return ctypeid-objectid for result.'
| def get_result_value(self, result):
| return ('%s-%s' % (ContentType.objects.get_for_model(result).pk, result.pk))
|
'Return the name of the model, fetch parent if model is a proxy'
| def get_model_name(self, model):
| if model._meta.proxy:
try:
model = list(model._meta.parents.keys())[0]
except IndexError:
pass
return model._meta.verbose_name
|
'Return the list of objects in the GM2MField relation.'
| def value_from_object(self, instance, name):
| return (None if (not instance.pk) else [getattr(x, 'gm2m_tgt', x) for x in getattr(instance, name).all()])
|
'Save the relation into the GM2MField.'
| def save_relation_data(self, instance, name, value):
| setattr(instance, name, value)
|
'Return the list of related objects.'
| def value_from_object(self, instance, name):
| return [x.object for x in getattr(instance, name).all()]
|
'Update the relation to be ``value``.'
| def save_relation_data(self, instance, name, value):
| instance_field = getattr(instance, name)
for related in instance_field.all():
if (related.object not in value):
instance_field.remove(related)
for related in value:
instance_field.connect(related)
|
'Render only selected tags.'
| def render_options(self, *args):
| selected_choices_arg = (1 if (VERSION < (1, 10)) else 0)
selected_choices = args[selected_choices_arg]
if selected_choices:
selected_choices = selected_choices.split(',')
options = [('<option value="%s" selected="selected">%s</option>' % (c, c)) for c in selected_choices]
return '\n'.j... |
'Return option, content type.'
| def create_option(self):
| option = super(AdminSelect2List, self).create_option()
option.test = random_text()
option.save()
return option
|
'Assert that it won\'t render unselected choices, if given a url.'
| def test_widget_renders_only_selected_with_url(self):
| class Form(forms.Form, ):
test = forms.ChoiceField(choices=[(i, ('label for %s' % i)) for i in range(0, 100)], widget=Select(url=reverse('test_url')), required=False)
form = Form(http.QueryDict('test=4'))
expected = ('\n<select data-autocomplete-light-url="/test-url/" id="id_test" nam... |
'Assert that it renders an empty option, if not given a url.'
| def test_widget_renders_empty_option_with_placeholder_without_url(self):
| class Form(forms.Form, ):
test = forms.ChoiceField(choices=[(1, 'A')], widget=Select2(attrs={'data-placeholder': 'Some placeholder'}), required=False)
form = Form(http.QueryDict())
expected = ('\n<select data-autocomplete-light-function="select2" data-placeholder="Some placeholder" id... |
'Assert that it renders an empty option, if not given a url.'
| def test_widget_no_empty_option_without_placeholder_without_url(self):
| class Form(forms.Form, ):
test = forms.ChoiceField(choices=[(1, 'A')], widget=Select2(), required=False)
form = Form(http.QueryDict())
expected = '\n<select data-autocomplete-light-function="select2" id="id_test" name="test">\n<option value="1">A</option>\n</select>\n ... |
':param (basestr, basestr) url, res_filename:
:return: (pubdate_failed, fulltext_failed)'
| @staticmethod
def check_url(args):
| (url, res_filename) = args
(pubdate_failed, fulltext_failed) = (False, False)
html = mock_resource_with(res_filename, 'html')
try:
a = Article(url)
a.download(html)
a.parse()
if (a.publish_date is None):
pubdate_failed = True
except Exception:
prin... |
'Called before the first test case of this unit begins'
| def setUp(self):
| self.article = Article(url='http://www.cnn.com/2013/11/27/travel/weather-thanksgiving/index.html?iref=allsearch')
|
'Calling `parse()` before `download()` should yield an error'
| @print_test
def test_pre_download_parse(self):
| article = Article(self.article.url)
self.assertRaises(ArticleException, article.parse)
|
'Test running NLP algos before even downloading the article'
| @print_test
def test_pre_download_nlp(self):
| self.setup_stage('initial')
new_article = Article(self.article.url)
self.assertRaises(ArticleException, new_article.nlp)
|
'Test running NLP algos before parsing the article'
| @print_test
def test_pre_parse_nlp(self):
| self.setup_stage('parse')
self.assertRaises(ArticleException, self.article.nlp)
|
'builds a source object, validates it has no errors, prints out
all valid categories and feed urls'
| @unittest.skip('Need to mock download')
@print_test
def test_source_build(self):
| DESC = 'CNN.com International delivers breaking news from across the globe and information on the latest top stories, business, sports and entertainment headlines. Follow the news as it happens through: special reports, videos... |
'Builds two same source objects in a row examines speeds of both'
| @unittest.skip('Need to mock download')
@print_test
def test_cache_categories(self):
| url = 'http://uk.yahoo.com'
html = mock_resource_with('yahoo_main_site', 'html')
s = Source(url)
s.download()
s.parse()
s.set_categories()
saved_urls = s.category_urls()
s.categories = []
s.set_categories()
self.assertCountEqual(saved_urls, s.category_urls())
|
'Prints out a list of urls with our heuristic guess if it is a
valid news url purely based on the url'
| @print_test
def test_valid_urls(self):
| from newspaper.urls import valid_url
with open(os.path.join(TEST_DIR, 'data/test_urls.txt'), 'r') as f:
lines = f.readlines()
test_tuples = [tuple(l.strip().split(' ')) for l in lines]
for (lst, url) in test_tuples:
truth_val = bool(int(lst))
try:
self.assertEq... |
'Normalizes a url, removes arguments, hashtags. If a relative url, it
merges it with the source domain to make an abs url, etc'
| @unittest.skip('Need to write an actual test')
@print_test
def test_prepare_url(self):
| pass
|
'Grab google trending, just make sure this runs'
| @print_test
def test_hot_trending(self):
| newspaper.hot()
|
'Just make sure this method runs'
| @print_test
def test_popular_urls(self):
| newspaper.popular_urls()
|
'Required to be called before the extraction process in some
cases because the stopwords_class has to set incase the lang
is not latin based'
| def update_language(self, meta_lang):
| if meta_lang:
self.language = meta_lang
self.stopwords_class = self.config.get_stopwords_class(meta_lang)
|
'Returns the body text of an article, and also the body article
html if specified. Returns in (text, html) form'
| def get_formatted(self, top_node):
| self.top_node = top_node
(html, text) = ('', '')
self.remove_negativescores_nodes()
if self.config.keep_article_html:
html = self.convert_to_html()
self.links_to_text()
self.add_newline_to_br()
self.add_newline_to_li()
self.replace_with_text()
self.remove_empty_tags()
sel... |
'Cleans up and converts any nodes that should be considered
text into text.'
| def links_to_text(self):
| self.parser.stripTags(self.get_top_node(), 'a')
|
'If there are elements inside our top node that have a
negative gravity score, let\'s give em the boot.'
| def remove_negativescores_nodes(self):
| gravity_items = self.parser.css_select(self.top_node, '*[gravityScore]')
for item in gravity_items:
score = self.parser.getAttribute(item, 'gravityScore')
score = (float(score) if score else 0)
if (score < 1):
item.getparent().remove(item)
|
'Replace common tags with just text so we don\'t have any crazy
formatting issues so replace <br>, <i>, <strong>, etc....
With whatever text is inside them.
code : http://lxml.de/api/lxml.etree-module.html#strip_tags'
| def replace_with_text(self):
| self.parser.stripTags(self.get_top_node(), 'b', 'strong', 'i', 'br', 'sup')
|
'It\'s common in top_node to exit tags that are filled with data
within properties but not within the tags themselves, delete them'
| def remove_empty_tags(self):
| all_nodes = self.parser.getElementsByTags(self.get_top_node(), ['*'])
all_nodes.reverse()
for el in all_nodes:
tag = self.parser.getTag(el)
text = self.parser.getText(el)
if (((tag != 'br') or (text != '\\r')) and (not text) and (len(self.parser.getElementsByTag(el, tag='object')) ==... |
'Punish the *last top level* node in the top_node if it\'s
DOM depth is too deep. Many media non-content links are
eliminated: "related", "loading gallery", etc'
| def remove_trailing_media_div(self):
| def get_depth(node, depth=1):
'Computes depth of an lxml element via BFS, this would be\n in parser if it were used anywhere else besides this method\n '
... |
'Abstraction of a threadpool. A newspool can accept any number of
source OR article objects together in a list. It allocates one
thread to every source and then joins.
We allocate one thread per source to avoid rate limiting.
5 sources = 5 threads, one per source.
>>> import newspaper
>>> from newspaper import news_poo... | def __init__(self, config=None):
| self.papers = []
self.pool = None
self.config = (config or Configuration())
|
'Runs the mtheading and returns when all threads have joined
resets the task.'
| def join(self):
| if (self.pool is None):
print 'Call set(..) with a list of source objects before .join(..)'
raise
self.pool.wait_completion()
self.papers = []
self.pool = None
|
'Modify any of these Article / Source properties
TODO: Have a separate ArticleConfig and SourceConfig extend this!'
| def __init__(self):
| self.MIN_WORD_COUNT = 300
self.MIN_SENT_COUNT = 7
self.MAX_TITLE = 200
self.MAX_TEXT = 100000
self.MAX_KEYWORDS = 35
self.MAX_AUTHORS = 10
self.MAX_SUMMARY = 5000
self.MAX_SUMMARY_SENT = 5
self.MAX_FILE_MEMO = 20000
self.memoize_articles = True
self.fetch_images = True
se... |
'Language setting must be set in this method b/c non-occidental
(western) languages require a seperate stopwords class.'
| def set_language(self, language):
| if ((not language) or (len(language) != 2)):
raise Exception('Your input language must be a 2 char language code, for example: english-->en \n and german-->de')
self.use_meta_language = False
... |
'Identifies top image, trims out a thumbnail and also has a url'
| def thumbnail(self):
| image_url = self.largest_image_url()
if image_url:
(content_type, image_str) = fetch_url(image_url, referer=self.url)
if image_str:
image = str_to_image(image_str)
try:
image = prepare_image(image)
except IOError as e:
if ('inte... |
'Create a video object from a video embed'
| def get_video(self, node):
| video = Video()
video.embed_code = self.get_embed_code(node)
video.embed_type = self.get_embed_type(node)
video.width = self.get_width(node)
video.height = self.get_height(node)
video.src = self.get_src(node)
video.provider = self.get_provider(video.src)
return video
|
'Extract html video tags'
| def get_video_tag(self, node):
| return Video()
|
'Set appropriate tag names and regexes of tags to remove
from the HTML'
| def __init__(self, config):
| self.config = config
self.parser = self.config.get_parser()
self.remove_nodes_re = '^side$|combx|retweet|mediaarticlerelated|menucontainer|navbar|storytopbar-bucket|utility-bar|inline-share-tools|comment|PopularQuestions|contact|foot|footer|Footer|footnote|cnn_strycaptiontxt|cnn_html_slideshow|cnn_strylftcn... |
'Remove chunks of the DOM as specified'
| def clean(self, doc_to_clean):
| doc_to_clean = self.clean_body_classes(doc_to_clean)
doc_to_clean = self.clean_article_tags(doc_to_clean)
doc_to_clean = self.clean_em_tags(doc_to_clean)
doc_to_clean = self.remove_drop_caps(doc_to_clean)
doc_to_clean = self.remove_scripts_styles(doc_to_clean)
doc_to_clean = self.clean_bad_tags(... |
'Removes the `class` attribute from the <body> tag because
if there is a bad match, the entire DOM will be empty!'
| def clean_body_classes(self, doc):
| elements = self.parser.getElementsByTag(doc, tag='body')
if elements:
self.parser.delAttribute(elements[0], attr='class')
return doc
|
'The config object for this source will be passed into all of this
source\'s children articles unless specified otherwise or re-set.'
| def __init__(self, url, config=None, **kwargs):
| if ((url is None) or ('://' not in url) or (url[:4] != 'http')):
raise Exception('Input url is bad!')
self.config = (config or Configuration())
self.config = utils.extend_config(self.config, kwargs)
self.extractor = ContentExtractor(self.config)
self.url = url
self.url = urls.pr... |
'Encapsulates download and basic parsing with lxml. May be a
good idea to split this into download() and parse() methods.'
| def build(self):
| self.download()
self.parse()
self.set_categories()
self.download_categories()
self.parse_categories()
self.set_feeds()
self.download_feeds()
self.generate_articles()
|
'Delete rejected articles, if there is an articles param,
purge from there, otherwise purge from source instance.
Reference this StackOverflow post for some of the wonky
syntax below:
http://stackoverflow.com/questions/1207406/remove-items-from-a-
list-while-iterating-in-python'
| def purge_articles(self, reason, articles):
| if (reason == 'url'):
articles[:] = [a for a in articles if a.is_valid_url()]
elif (reason == 'body'):
articles[:] = [a for a in articles if a.is_valid_body()]
return articles
|
'The domain param is **necessary**, see .utils.cache_disk for reasons.
the boilerplate method is so we can use this decorator right.
We are caching categories for 1 day.'
| @utils.cache_disk(seconds=(86400 * 1), cache_folder=ANCHOR_DIRECTORY)
def _get_category_urls(self, domain):
| return self.extractor.get_category_urls(self.url, self.doc)
|
'Don\'t need to cache getting feed urls, it\'s almost
instant with xpath'
| def set_feeds(self):
| common_feed_urls = ['/feed', '/feeds', '/rss']
common_feed_urls = [urljoin(self.url, url) for url in common_feed_urls]
split = urlsplit(self.url)
if (split.netloc in ('medium.com', 'www.medium.com')):
if split.path.startswith('/@'):
new_path = ('/feed/' + split.path.split('/')[1])
... |
'Sets a blurb for this source, for now we just query the
desc html attribute'
| def set_description(self):
| desc = self.extractor.get_meta_description(self.doc)
self.description = desc
|
'Downloads html of source'
| def download(self):
| self.html = network.get_html(self.url, self.config)
|
'Download all category html, can use mthreading'
| def download_categories(self):
| category_urls = [c.url for c in self.categories]
requests = network.multithread_request(category_urls, self.config)
for (index, _) in enumerate(self.categories):
req = requests[index]
if (req.resp is not None):
self.categories[index].html = network.get_html(req.url, response=req.... |
'Download all feed html, can use mthreading'
| def download_feeds(self):
| feed_urls = [f.url for f in self.feeds]
requests = network.multithread_request(feed_urls, self.config)
for (index, _) in enumerate(self.feeds):
req = requests[index]
if (req.resp is not None):
self.feeds[index].rss = network.get_html(req.url, response=req.resp)
elif self.... |
'Sets the lxml root, also sets lxml roots of all
children links, also sets description'
| def parse(self):
| self.doc = self.config.get_parser().fromstring(self.html)
if (self.doc is None):
print ('[Source parse ERR]', self.url)
return
self.set_description()
|
'Parse out the lxml root in each category'
| def parse_categories(self):
| log.debug(('We are extracting from %d categories' % len(self.categories)))
for category in self.categories:
doc = self.config.get_parser().fromstring(category.html)
category.doc = doc
self.categories = [c for c in self.categories if (c.doc is not None)]
|
'Add titles to feeds'
| def parse_feeds(self):
| log.debug(('We are parsing %d feeds' % len(self.feeds)))
self.feeds = [self._map_title_to_feed(f) for f in self.feeds]
|
'Returns articles given the url of a feed'
| def feeds_to_articles(self):
| articles = []
for feed in self.feeds:
urls = self.extractor.get_urls(feed.rss, regex=True)
cur_articles = []
before_purge = len(urls)
for url in urls:
article = Article(url=url, source_url=self.url, config=self.config)
cur_articles.append(article)
... |
'Takes the categories, splays them into a big list of urls and churns
the articles out of each url with the url_to_article method'
| def categories_to_articles(self):
| articles = []
for category in self.categories:
cur_articles = []
url_title_tups = self.extractor.get_urls(category.doc, titles=True)
before_purge = len(url_title_tups)
for tup in url_title_tups:
indiv_url = tup[0]
indiv_title = tup[1]
_article ... |
'Returns a list of all articles, from both categories and feeds'
| def _generate_articles(self):
| category_articles = self.categories_to_articles()
feed_articles = self.feeds_to_articles()
articles = (feed_articles + category_articles)
uniq = {article.url: article for article in articles}
return list(uniq.values())
|
'Saves all current articles of news source, filter out bad urls'
| def generate_articles(self, limit=5000):
| articles = self._generate_articles()
self.articles = articles[:limit]
log.debug('%d articles generated and cutoff at %d', len(articles), limit)
|
'Downloads all articles attached to self'
| def download_articles(self, threads=1):
| urls = [a.url for a in self.articles]
failed_articles = []
if (threads == 1):
for (index, article) in enumerate(self.articles):
url = urls[index]
html = network.get_html(url, config=self.config)
self.articles[index].set_html(html)
if (not html):
... |
'Parse all articles, delete if too small'
| def parse_articles(self):
| for (index, article) in enumerate(self.articles):
article.parse()
self.articles = self.purge_articles('body', self.articles)
self.is_parsed = True
|
'Number of articles linked to this news source'
| def size(self):
| if (self.articles is None):
return 0
return len(self.articles)
|
'Clears the memoization cache for this specific news domain'
| def clean_memo_cache(self):
| utils.clear_memo_cache(self)
|
'Returns a list of feed urls'
| def feed_urls(self):
| return [feed.url for feed in self.feeds]
|
'Returns a list of category urls'
| def category_urls(self):
| return [category.url for category in self.categories]
|
'Returns a list of article urls'
| def article_urls(self):
| return [article.url for article in self.articles]
|
'Prints out a summary of the data in our source instance'
| def print_summary(self):
| print ('[source url]:', self.url)
print ('[source brand]:', self.brand)
print ('[source domain]:', self.domain)
print ('[source len(articles)]:', len(self.articles))
print ('[source description[:50]]:', self.description[:50])
print 'printing out 10 sample articles...'
... |
'Required to be called before the extraction process in some
cases because the stopwords_class has to set incase the lang
is not latin based'
| def update_language(self, meta_lang):
| if meta_lang:
self.language = meta_lang
self.stopwords_class = self.config.get_stopwords_class(meta_lang)
|
'Fetch the authors of the article, return as a list
Only works for english articles'
| def get_authors(self, doc):
| _digits = re.compile('\\d')
def contains_digits(d):
return bool(_digits.search(d))
def uniqify_list(lst):
'Remove duplicates from provided list but maintain original order.\n Derived from http://www.peterbe.... |
'3 strategies for publishing date extraction. The strategies
are descending in accuracy and the next strategy is only
attempted if a preferred one fails.
1. Pubdate from URL
2. Pubdate from metadata
3. Raw regex searches in the HTML + added heuristics'
| def get_publishing_date(self, url, doc):
| def parse_date_str(date_str):
if date_str:
try:
return date_parser(date_str)
except (ValueError, OverflowError, AttributeError):
return None
date_match = re.search(urls.DATE_REGEX, url)
if date_match:
date_str = date_match.group(0)
... |
'Fetch the article title and analyze it
Assumptions:
- title tag is the most reliable (inherited from Goose)
- h1, if properly detected, is the best (visible to users)
- og:title and h1 can help improve the title extraction
- python == is too strict, often we need to compare filtered
versions, i.e. lowercase and ignori... | def get_title(self, doc):
| title = ''
title_element = self.parser.getElementsByTag(doc, tag='title')
if ((title_element is None) or (len(title_element) == 0)):
return title
title_text = self.parser.getText(title_element[0])
used_delimeter = False
title_text_h1 = ''
title_element_h1_list = (self.parser.getEleme... |
'Split the title to best part possible'
| def split_title(self, title, splitter, hint=None):
| large_text_length = 0
large_text_index = 0
title_pieces = splitter.split(title)
if hint:
filter_regex = re.compile('[^a-zA-Z0-9\\ ]')
hint = filter_regex.sub('', hint).lower()
for (i, title_piece) in enumerate(title_pieces):
current = title_piece.strip()
if (hint a... |
'Takes a source url and a list of category objects and returns
a list of feed urls'
| def get_feed_urls(self, source_url, categories):
| total_feed_urls = []
for category in categories:
kwargs = {'attr': 'type', 'value': 'application\\/rss\\+xml'}
feed_elements = self.parser.getElementsByTag(category.doc, **kwargs)
feed_urls = [e.get('href') for e in feed_elements if e.get('href')]
total_feed_urls.extend(feed_urls... |
'Extract the favicon from a website http://en.wikipedia.org/wiki/Favicon
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<link rel="icon" type="image/png" href="favicon.png" />'
| def get_favicon(self, doc):
| kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'icon'}
meta = self.parser.getElementsByTag(doc, **kwargs)
if meta:
favicon = self.parser.getAttribute(meta[0], 'href')
return favicon
return ''
|
'Extract content language from meta'
| def get_meta_lang(self, doc):
| attr = self.parser.getAttribute(doc, attr='lang')
if (attr is None):
items = [{'tag': 'meta', 'attr': 'http-equiv', 'value': 'content-language'}, {'tag': 'meta', 'attr': 'name', 'value': 'lang'}]
for item in items:
meta = self.parser.getElementsByTag(doc, **item)
if meta:... |
'Extract a given meta content form document.
Example metaNames:
"meta[name=description]"
"meta[name=keywords]"
"meta[property=og:type]"'
| def get_meta_content(self, doc, metaname):
| meta = self.parser.css_select(doc, metaname)
content = None
if ((meta is not None) and (len(meta) > 0)):
content = self.parser.getAttribute(meta[0], 'content')
if content:
return content.strip()
return ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.