rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
try: from htmlentitydefs import name2codepoint, codepoint2name except: import htmlentitydefs name2codepoint={} codepoint2name={} for (name,codepoint) in htmlentitydefs.entitydefs.iteritems(): if codepoint.startswith('& name2codepoint[name]=ord(codepoint) codepoint2name[ord(codepoint)]=name BeautifulSoup = None
def _xmlescape(data,entities={}): data = data.replace('&', '&amp;') data = data.replace('>', '&gt;') data = data.replace('<', '&lt;') for char, entity in entities: data = data.replace(char, entity) return data
sgmllib.charref = re.compile('& if sgmllib.endbracket.search(' <').start(0): class EndBracketMatch: endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''') def search(self,string,index=0): self.match = self.endbracket.match(string,index) if self.match: return self de...
sgmllib.charref = re.compile('&
def _xmlescape(data,entities={}): data = data.replace('&', '&amp;') data = data.replace('>', '&gt;') data = data.replace('<', '&lt;') for char, entity in entities: data = data.replace(char, entity) return data
if key == 'enclosures': norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel']) return [norel(link) for link in UserDict.__getitem__(self, 'links') if link['rel']=='enclosure']
def __getitem__(self, key): if key == 'category': return UserDict.__getitem__(self, 'tags')[0]['term'] if key == 'enclosures': norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel']) return [norel(link) for link in UserDict.__getitem__(self, 'links') if link['rel']=='enclosur...
_cp1252 = { unichr(128): unichr(8364), unichr(130): unichr(8218), unichr(131): unichr( 402), unichr(132): unichr(8222), unichr(133): unichr(8230), unichr(134): unichr(8224), unichr(135): unichr(8225), unichr(136): unichr( 710), unichr(137): unichr(8240), unichr(138): unichr( 352), unichr(139): unichr(8249), unichr(140)...
def _ebcdic_to_ascii(s): global _ebcdic_to_ascii_map if not _ebcdic_to_ascii_map: emap = ( 0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, 32,160,161,...
try: return urlparse.urljoin(base, uri) except: uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)]) return urlparse.urljoin(base, uri)
return urlparse.urljoin(base, uri)
def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) try: return urlparse.urljoin(base, uri) except: uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)]) return urlparse.urljoin(base, uri)
'http://www.w3.org/1999/xlink': 'xlink',
def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) try: return urlparse.urljoin(base, uri) except: uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)]) return urlparse.urljoin(base, uri)
self.feeddata['language'] = baselang.replace('_','-')
self.feeddata['language'] = baselang
def __init__(self, baseuri=None, baselang=None, encoding='utf-8'): if _debug: sys.stderr.write('initializing FeedParser\n') if not self._matchnamespaces: for k, v in self.namespaces.items(): self._matchnamespaces[k.lower()] = v self.feeddata = FeedParserDict() # feed-level data self.encoding = encoding # character enco...
self.feeddata['language'] = lang.replace('_','-')
self.feeddata['language'] = lang
def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:bas...
if tag.find(':') <> -1: prefix, tag = tag.split(':', 1) namespace = self.namespacesInUse.get(prefix, '') if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrs.append(('xmlns',namespace)) if tag=='svg' and namespace=='http://www.w3.org/2000/svg': attrs.append(('xmlns',namespace)) return self.handle_d...
tag = tag.split(':')[-1] return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0)
def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:bas...
elif ref in self.entities.keys(): text = self.entities[ref] if text.startswith('& return self.handle_entityref(text) else: try: name2codepoint[ref]
else: def name2cp(k): import htmlentitydefs if hasattr(htmlentitydefs, 'name2codepoint'): return htmlentitydefs.name2codepoint[k] k = htmlentitydefs.entitydefs[k] if k.startswith('& return int(k[2:-1]) return ord(k) try: name2cp(ref)
def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' if not self.elementstack: return if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref) if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): text = '&%s;' % ref elif ref in self.entities.keys(): text =...
else: text = unichr(name2codepoint[ref]).encode('utf-8')
else: text = unichr(name2cp(ref)).encode('utf-8')
def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' if not self.elementstack: return if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref) if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): text = '&%s;' % ref elif ref in self.entities.keys(): text =...
def strattrs(self, attrs): return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs])
def strattrs(self, attrs): return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs])
if self.version == 'atom10' and self.contentparams.get('type','text') == 'application/xhtml+xml': while pieces and len(pieces)>1 and not pieces[-1].strip(): del pieces[-1] while pieces and len(pieces)>1 and not pieces[0].strip(): del pieces[0] if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) an...
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
if self.lookslikehtml(output): self.contentparams['type']='text/html'
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
is_htmlish = self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
if is_htmlish:
if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', 'text/html')) if is_htmlish and element in ['content', 'description', 'summary']: mfresults = _parseMicroformats(output, self.baseuri, self.encoding) if mfresults: for tag in mfresults.get('tags', []): self._addTag(tag...
output = _resolveRelativeURIs(output, self.baseuri, self.encoding)
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', 'text/html'))
output = _sanitizeHTML(output, self.encoding)
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
if self.encoding=='utf-8' and type(output) == type(u''): try: output = unicode(output.encode('iso-8859-1'), 'utf-8') except: pass if type(output) == type(u''): output = u''.join([c in _cp1252.keys() and _cp1252[c] or c for c in output])
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
elif (self.infeed or self.insource):
elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage):
def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop()
if self.lang: self.lang=self.lang.replace('_','-')
def pushContent(self, tag, attrsD, defaultContentType, expectingText): self.incontent += 1 if self.lang: self.lang=self.lang.replace('_','-') self.contentparams = FeedParserDict({ 'type': self.mapContentType(attrsD.get('type', defaultContentType)), 'language': self.lang, 'base': self.baseuri}) self.contentparams['base6...
def lookslikehtml(self, str): if self.version.startswith('atom'): return if self.contentparams.get('type','text/html') != 'text/plain': return if not (re.search(r'</(\w+)>',str) or re.search("& if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements, re.findall(r'</?(\w+)',str)): return from htmle...
def popContent(self, tag): value = self.pop(tag) self.incontent -= 1 self.contentparams.clear() return value
self.inimage = 1 self.push('image', 0)
def _start_image(self, attrsD): context = self._getContext() context.setdefault('image', FeedParserDict()) self.inimage = 1 self.push('image', 0)
self.intextinput = 1 self.push('textinput', 0)
def _start_textinput(self, attrsD): context = self._getContext() context.setdefault('textinput', FeedParserDict()) self.intextinput = 1 self.push('textinput', 0)
context['name'] = value
context['textinput']['name'] = value
def _end_name(self): value = self.pop('name') if self.inpublisher: self._save_author('name', value, 'publisher') elif self.inauthor: self._save_author('name', value) elif self.incontributor: self._save_contributor('name', value) elif self.intextinput: context = self._getContext() context['name'] = value
context['width'] = value
context['image']['width'] = value
def _end_width(self): value = self.pop('width') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['width'] = value
context['height'] = value
context['image']['height'] = value
def _end_height(self): value = self.pop('height') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['height'] = value
elif self.inimage: context = self.feeddata['image'] elif self.intextinput: context = self.feeddata['textinput']
def _getContext(self): if self.insource: context = self.sourcedata elif self.inimage: context = self.feeddata['image'] elif self.intextinput: context = self.feeddata['textinput'] elif self.inentry: context = self.entries[-1] else: context = self.feeddata return context
author, email = context.get(key), None
author = context.get(key)
def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = '%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author, ema...
emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author) if emailmatch: email = emailmatch.group(0) author = author.replace(email, '') author = author.replace('()', '') author = author.replace('<>', '...
emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''', author) if not emailmatch: return email = emailmatch.group(0) author = author.replace(email, '') author = author.replace('()', '') author = author.strip() if author an...
def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = '%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author, ema...
def _addXFN(self, relationships, href, name): context = self._getContext() xfn = context.setdefault('xfn', []) value = FeedParserDict({'relationships': relationships, 'href': href, 'name': name}) if value not in xfn: xfn.append(value)
def _addXFN(self, relationships, href, name): context = self._getContext() xfn = context.setdefault('xfn', []) value = FeedParserDict({'relationships': relationships, 'href': href, 'name': name}) if value not in xfn: xfn.append(value)
tags.append(value)
tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label}))
def _addTag(self, term, scheme, label): context = self._getContext() tags = context.setdefault('tags', []) if (not term) and (not scheme) and (not label): return value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label}) if value not in tags: tags.append(value)
if attrsD['rel'] == 'self': attrsD.setdefault('type', 'application/atom+xml') else: attrsD.setdefault('type', 'text/html') context = self._getContext()
attrsD.setdefault('type', 'text/html')
def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') if attrsD['rel'] == 'self': attrsD.setdefault('type', 'application/atom+xml') else: attrsD.setdefault('type', 'text/html') context = self._getContext() attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(...
if attrsD.get('rel')=='enclosure' and not context.get('id'): context['id'] = attrsD.get('href')
def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') if attrsD['rel'] == 'self': attrsD.setdefault('type', 'application/atom+xml') else: attrsD.setdefault('type', 'text/html') context = self._getContext() attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(...
if self.incontent: return self.unknown_starttag('title', attrsD)
def _start_title(self, attrsD): if self.incontent: return self.unknown_starttag('title', attrsD) self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
if not value: return
def _end_title(self): value = self.popContent('title') if not value: return context = self._getContext()
_start_dc_description = _start_description
def _start_description(self, attrsD): context = self._getContext() if context.has_key('summary'): self._summaryKey = 'content' self._start_content(attrsD) else: self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
_end_dc_description = _end_description
def _end_description(self): if self._summaryKey == 'content': self._end_content() else: value = self.popContent('description') self._summaryKey = None
context = self._getContext() attrsD['rel']='enclosure' context.setdefault('links', []).append(FeedParserDict(attrsD))
self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD))
def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) context = self._getContext() attrsD['rel']='enclosure' context.setdefault('links', []).append(FeedParserDict(attrsD)) href = attrsD.get('href') if href and not context.get('id'): context['id'] = href
if href and not context.get('id'): context['id'] = href
if href: context = self._getContext() if not context.get('id'): context['id'] = href
def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) context = self._getContext() attrsD['rel']='enclosure' context.setdefault('links', []).append(FeedParserDict(attrsD)) href = attrsD.get('href') if href and not context.get('id'): context['id'] = href
if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrsD['xmlns']=namespace if localname=='svg' and namespace=='http://www.w3.org/2000/svg': attrsD['xmlns']=namespace if prefix: localname = prefix.lower() + ':' + localname elif namespace and not qname: for name,value in self.namespacesInUse.ite...
def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') <> -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':...
elif namespace and not qname: for name,value in self.namespacesInUse.items(): if name and value == namespace: localname = name + ':' + localname break
def endElementNS(self, name, qname): namespace, localname = name lowernamespace = str(namespace or '').lower() if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = '' prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if prefix: localname = prefix + ':' + localname elif n...
special = re.compile('''[<>'"]''') bare_ampersand = re.compile("&(?!
def fatalError(self, exc): self.error(exc) raise exc
def __init__(self, encoding, type):
def __init__(self, encoding):
def __init__(self, encoding, type): self.encoding = encoding self.type = type if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding) sgmllib.SGMLParser.__init__(self)
self.type = type
def __init__(self, encoding, type): self.encoding = encoding self.type = type if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding) sgmllib.SGMLParser.__init__(self)
def parse_starttag(self,i): j=sgmllib.SGMLParser.parse_starttag(self, i) if self.type == 'application/xhtml+xml': if j>2 and self.rawdata[j-2:j]=='/>': self.unknown_endtag(self.lasttag) return j
def _shorttag_replace(self, match): tag = match.group(1) if tag in self.elements_no_end_tag: return '<' + tag + ' />' else: return '<' + tag + '></' + tag + '>'
sgmllib.SGMLParser.close(self)
def feed(self, data): data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data) #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) data = data.replace('&#39;', "'") data...
if not attrs: return attrs
def normalize_attrs(self, attrs): if not attrs: return attrs # utility method to be called by descendants attrs = dict([(k.lower(), v) for k, v in attrs]).items() attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] attrs.sort() return attrs
attrs = dict([(k.lower(), v) for k, v in attrs]).items()
attrs = [(k.lower(), v) for k, v in attrs]
def normalize_attrs(self, attrs): if not attrs: return attrs # utility method to be called by descendants attrs = dict([(k.lower(), v) for k, v in attrs]).items() attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] attrs.sort() return attrs
attrs.sort()
def normalize_attrs(self, attrs): if not attrs: return attrs # utility method to be called by descendants attrs = dict([(k.lower(), v) for k, v in attrs]).items() attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] attrs.sort() return attrs
strattrs='' if attrs: for key, value in attrs: value=value.replace('>','&gt;').replace('<','&lt;').replace('"','&quot;') value = self.bare_ampersand.sub("&amp;", value) if type(value) != type(u''): try: value = unicode(value, self.encoding) except: value = unicode(value, 'iso-8859-1') uattrs.append((unicode(key, self....
for key, value in attrs: if type(value) != type(u''): value = unicode(value, self.encoding) uattrs.append((unicode(key, self.encoding), value)) strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
def unknown_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')] if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag) uattrs = [] strattrs='' if attrs: for key, value in at...
if ref.startswith('x'): value = unichr(int(ref[1:],16)) else: value = unichr(int(ref)) if value in _cp1252.keys(): self.pieces.append('& else: self.pieces.append('&
self.pieces.append('&
def handle_charref(self, ref): # called for each character reference, e.g. for '&#160;', ref will be '160' # Reconstruct the original character reference. if ref.startswith('x'): value = unichr(int(ref[1:],16)) else: value = unichr(int(ref))
if name2codepoint.has_key(ref): self.pieces.append('&%(ref)s;' % locals()) else: self.pieces.append('&amp;%(ref)s' % locals())
self.pieces.append('&%(ref)s;' % locals())
def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' # Reconstruct the original entity reference. if name2codepoint.has_key(ref): self.pieces.append('&%(ref)s;' % locals()) else: self.pieces.append('&amp;%(ref)s' % locals())
def convert_charref(self, name): return '& def convert_entityref(self, name): return '&%s;' % name
def convert_charref(self, name): return '&#%s;' % name
def __init__(self, baseuri, baselang, encoding, entities):
def __init__(self, baseuri, baselang, encoding):
def __init__(self, baseuri, baselang, encoding, entities): sgmllib.SGMLParser.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) _BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml') self.entities=entities
_BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml') self.entities=entities
def __init__(self, baseuri, baselang, encoding, entities): sgmllib.SGMLParser.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) _BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml') self.entities=entities
data = data.replace('&
def decodeEntities(self, element, data): data = data.replace('&#60;', '&lt;') data = data.replace('&#x3c;', '&lt;') data = data.replace('&#x3C;', '&lt;') data = data.replace('&#62;', '&gt;') data = data.replace('&#x3e;', '&gt;') data = data.replace('&#x3E;', '&gt;') data = data.replace('&#38;', '&amp;') data = data.rep...
def strattrs(self, attrs): return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs]) class _MicroformatsParser: STRING = 1 DATE = 2 URI = 3 NODE = 4 EMAIL = 5 known_xfn_relationships = ['contact', 'acquaintance', 'friend', 'met', 'co-worker', 'coworker', 'colleague', 'co-resident', 'coresident', 'ne...
def strattrs(self, attrs): return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs])
def __init__(self, baseuri, encoding, type): _BaseHTMLProcessor.__init__(self, encoding, type)
def __init__(self, baseuri, encoding): _BaseHTMLProcessor.__init__(self, encoding)
def __init__(self, baseuri, encoding, type): _BaseHTMLProcessor.__init__(self, encoding, type) self.baseuri = baseuri
return _urljoin(self.baseuri, uri.strip())
return _urljoin(self.baseuri, uri)
def resolveURI(self, uri): return _urljoin(self.baseuri, uri.strip())
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type):
def _resolveRelativeURIs(htmlSource, baseURI, encoding):
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) p.feed(htmlSource) return p.output()
p = _RelativeURIResolver(baseURI, encoding, type)
p = _RelativeURIResolver(baseURI, encoding)
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) p.feed(htmlSource) return p.output()
'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label...
'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label...
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) p.feed(htmlSource) return p.output()
acceptable_css_properties = ['azimuth', 'background-color', 'border-bottom-color', 'border-collapse', 'border-color', 'border-left-color', 'border-right-color', 'border-top-color', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant',...
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) p.feed(htmlSource) return p.output()
self.mathmlOK = 0 self.svgOK = 0
def reset(self): _BaseHTMLProcessor.reset(self) self.unacceptablestack = 0 self.mathmlOK = 0 self.svgOK = 0
acceptable_attributes = self.acceptable_attributes keymap = {} if not tag in self.acceptable_elements or self.svgOK:
if not tag in self.acceptable_elements:
def unknown_starttag(self, tag, attrs): acceptable_attributes = self.acceptable_attributes keymap = {} if not tag in self.acceptable_elements or self.svgOK: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1
if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs: self.mathmlOK = 1 if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs: self.svgOK = 1 if self.mathmlOK and tag in self.mathml_elements: acceptable_attributes = self.mathml_attributes elif self.svgOK and tag in self.svg_elements...
return attrs = self.normalize_attrs(attrs) attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
def unknown_starttag(self, tag, attrs): acceptable_attributes = self.acceptable_attributes keymap = {} if not tag in self.acceptable_elements or self.svgOK: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1
if self.mathmlOK and tag in self.mathml_elements: if tag == 'math': self.mathmlOK = 0 elif self.svgOK and tag in self.svg_elements: tag = self.svg_elem_map.get(tag,tag) if tag == 'svg': self.svgOK = 0 else: return
return
def unknown_endtag(self, tag): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack -= 1 if self.mathmlOK and tag in self.mathml_elements: if tag == 'math': self.mathmlOK = 0 elif self.svgOK and tag in self.svg_elements: tag = self.svg_elem_map.get(tag,tag) i...
def sanitize_style(self, style): style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style) if not re.match("""^([:,; if not re.match("^(\s*[-\w]+\s*:\s*[^:;]*(;|$))*$", style): return '' clean = [] for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style): if not value: continue if prop.lower() in self.acc...
def _sanitizeHTML(htmlSource, encoding): p = _HTMLSanitizer(encoding)
def sanitize_style(self, style): # disallow urls style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
If the modified argument is supplied, it can be a tuple of 9 integers (as returned by gmtime() in the standard Python time module) or a date string in any format supported by feedparser. Regardless, it MUST be in GMT (Greenwich Mean Time). It will be reformatted into an RFC 1123-compliant date and used as the value of ...
If the modified argument is supplied, it must be a tuple of 9 integers as returned by gmtime() in the standard Python time module. This MUST be in GMT (Greenwich Mean Time). The formatted date/time will be used as the value of an If-Modified-Since request header.
def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i...
try: if isinstance(url_file_stream_or_string,unicode): url_file_stream_or_string = url_file_stream_or_string.encode('idna') else: url_file_stream_or_string = url_file_stream_or_string.decode('utf-8').encode('idna') except: pass
def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i...
if type(modified) == type(''): modified = _parse_date(modified)
def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i...
_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO',
_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
def registerDateHandler(func): '''Register a date handler function (takes string, returns 9-tuple date in GMT)''' _date_handlers.insert(0, func)
+ r'(:(?P<second>\d{2}(\.\d*)?))?'
+ r'(:(?P<second>\d{2}))?'
def registerDateHandler(func): '''Register a date handler function (takes string, returns 9-tuple date in GMT)''' _date_handlers.insert(0, func)
second = int(float(params.get('second', 0)))
second = int(params.get('second', 0))
def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal...
daylight_savings_flag = -1
daylight_savings_flag = 0
def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal...
entity_results=entity_pattern.findall(data)
def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) entity_results=entity_pattern.findall(data) data = entity...
replacement='' if len(doctype_results)==1 and entity_results: safe_pattern=re.compile('\s+(\w+)\s+"(& safe_entities=filter(lambda e: safe_pattern.match(e),entity_results) if safe_entities: replacement='<!DOCTYPE feed [\n <!ENTITY %s>\n]>' % '>\n <!ENTITY '.join(safe_entities) data = doctype_pattern.sub(replacement, d...
data = doctype_pattern.sub('', data) return version, data
def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) entity_results=entity_pattern.findall(data) data = entity...
result['version'], data, entities = _stripDoctype(data)
result['version'], data = _stripDoctype(data)
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:...
if (not known_encoding) and ('iso-8859-2' not in tried_encodings): try: proposed_encoding = 'iso-8859-2' tried_encodings.append(proposed_encoding) data = _toUTF8(data, proposed_encoding) known_encoding = use_strict_parser = 1 except: pass
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:...
'%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % \
'%s, %s, utf-8, and windows-1252 but nothing worked' % \
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:...
feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '', entities)
feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '')
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:...
class Serializer: def __init__(self, results): self.results = results class TextSerializer(Serializer): def write(self, stream=sys.stdout): self._writer(stream, self.results, '') def _writer(self, stream, node, prefix): if not node: return if hasattr(node, 'keys'): keys = node.keys() keys.sort() for k in keys: if k i...
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:...
try: from optparse import OptionParser except: OptionParser = None if OptionParser: optionParser = OptionParser(version=__version__, usage="%prog [options] url_or_filename_or_-") optionParser.set_defaults(format="pprint") optionParser.add_option("-A", "--user-agent", dest="agent", metavar="AGENT", help="User-Agent for...
if not sys.argv[1:]: print __doc__ sys.exit(0)
def write(self, stream=sys.stdout): stream.write(self.results['href'] + '\n\n') from pprint import pprint pprint(self.results, stream) stream.write('\n')
if not sys.argv[1:]: print __doc__ sys.exit(0) class _Options: etag = modified = agent = referrer = None format = 'pprint' options = _Options()
def write(self, stream=sys.stdout): stream.write(self.results['href'] + '\n\n') from pprint import pprint pprint(self.results, stream) stream.write('\n')
serializer = globals().get(options.format.capitalize() + 'Serializer', Serializer)
from pprint import pprint
def write(self, stream=sys.stdout): stream.write(self.results['href'] + '\n\n') from pprint import pprint pprint(self.results, stream) stream.write('\n')
results = parse(url, etag=options.etag, modified=options.modified, agent=options.agent, referrer=options.referrer) serializer(results).write(sys.stdout)
print url print result = parse(url) pprint(result) print
def write(self, stream=sys.stdout): stream.write(self.results['href'] + '\n\n') from pprint import pprint pprint(self.results, stream) stream.write('\n')
if not ('channel' in f and 'items'in f):
if not f['channel']:
def add_feed(feed_xml): """Try to add a feed. Return values: tuple (status, feed_uid) -1: unknown error 0: feed added normally 1: feed added via autodiscovery 2: feed not added, already present 3: feed not added, connection or parse error""" from singleton import db c = db.cursor() try: f = feedparser.parse(feed_xml) n...
unacceptable_elements_with_end_tag = ['script', 'applet']
unacceptable_elements_with_end_tag = ['script', 'applet', 'style']
def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) p.feed(htmlSource) return p.output()
reload(self.tmpl_cache[tmpl])
del self.tmpl_cache[tmpl]
def use_template(self, tmpl, searchlist): """Use compiled-on-demand versions of Cheetah templates for speed, specially with CGI """ self.set_mime_type(tmpl) tmpl = tmpl.replace('.', '_') modname = 'pages/' + tmpl page = modname + '.tmpl' compiled = modname + '.py' try: compiled_t = os.stat(compiled)[stat.ST_CTIME] exce...
if not (f.get('channel') and f.get('items')):
if not ('channel' in f and 'items'in f):
def add_feed(feed_xml): """Try to add a feed. Return values: -1: unknown error 0: feed added normally 1: feed added via autodiscovery 2: feed not added, already present 3: feed not added, connection or parse error""" from singleton import db c = db.cursor() try: f = feedparser.parse(feed_xml) normalize.normalize_feed(f...
punctuation = ''.join( [{True: c, False: ' '}[c in (string.letters + string.digits)] for c in [chr(x) for x in range(256)]])
punctuation = ',.?!;:-()' punct_map = {} for c in punctuation: punct_map[ord(c)] = 32
def fix_date(date_tuple): if not date_tuple: return date_tuple if date_tuple > time.gmtime(): # feedparser's parsed date tuple has no DST indication, we need to force it # because there is no UTC equivalent of mktime() date_tuple = date_tuple[:-1] + (-1,) date_tuple = time.localtime(time.mktime(date_tuple) - 3600) # if...
item['title_words'] = str(item['title_lc']).translate(punctuation).split()
item['title_words'] = unicode(item['title_lc']).translate(punct_map).split()
def normalize(item, f): # get rid of RDF lossage... for key in ['title', 'link', 'created', 'modified', 'author', 'content', 'content_encoded', 'description']: if type(item.get(key)) == list and len(item[key]) == 1: item[key] = item[key][0] if isinstance(item.get(key), dict) and 'value' in item[key]: item[key] = item[k...
codepoint = int('0x' + ent[2:])
codepoint = int('0x' + ent[2:], 16)
def ent_sub(m): ent = m.groups()[0] if ent in htmlentitydefs.name2codepoint: return unichr(htmlentitydefs.name2codepoint[ent]) if ent.startswith('#'): if ent.lower().startswith('#x'): codepoint = int('0x' + ent[2:]) else: codepoint = int(ent[1:]) if codepoint > 0 and codepoint < sys.maxunicode: return unichr(codepoint)...
if time.mktime(date_tuple) > time.mktime(time.gmtime()):
if time.mktime(date_tuple) > time.time():
def fix_date(date_tuple): if not date_tuple: return date_tuple if time.mktime(date_tuple) > time.mktime(time.gmtime()): # feedparser's parsed date tuple has no DST indication, we need to force it # because there is no UTC equivalent of mktime() date_tuple = date_tuple[:-1] + (-1,) date_tuple = time.localtime(time.mktim...
print >> param.log, str(e) + ', sleeping for', backoff
if param.debug: print >> param.log, thread.get_ident(), time.time(), str(e), print >> param.log, 'sleeping for', backoff
def execute(self, *args, **kwargs): from pysqlite2 import dbapi2 as sqlite before = time.time() backoff = 0.1 done = False while not done: try: result = self.c.execute(*args, **kwargs) done = True except sqlite.OperationalError, e: print >> param.log, str(e) + ', sleeping for', backoff time.sleep(backoff) backoff = min...
if elapsed > 5.0: print >> param.log, 'Slow SQL:', elapsed, args, kwargs
if param.debug: if elapsed > 5.0: print >> param.log, 'Slow SQL:', elapsed, args, kwargs print >> param.log, thread.get_ident(), time.time(), 'done'
def execute(self, *args, **kwargs): from pysqlite2 import dbapi2 as sqlite before = time.time() backoff = 0.1 done = False while not done: try: result = self.c.execute(*args, **kwargs) done = True except sqlite.OperationalError, e: print >> param.log, str(e) + ', sleeping for', backoff time.sleep(backoff) backoff = min...
print >> param.log, str(e) + ', sleeping for', backoff
if param.debug: print >> param.log, thread.get_ident(), time.time(), str(e), print >> param.log, 'sleeping for', backoff
def commit_wrapper(method): """Provide locking error recovery for commit/rollback""" from pysqlite2 import dbapi2 as sqlite backoff = 0.1 done = False while not done: try: method() done = True except sqlite.OperationalError, e: print >> param.log, str(e) + ', sleeping for', backoff time.sleep(backoff) backoff = min(bac...
if elapsed > 5.0:
if param.debug and elapsed > 5.0:
def execute(self, *args, **kwargs): before = time.time() result = self.c.execute(*args, **kwargs) elapsed = time.time() - before if elapsed > 5.0: print >> param.log, 'Slow SQL:', elapsed, args, kwargs return result
self.connect('key-press-event', self.key_press_event_cb)
self.connect('key-press-event', self.key_press_event_cb_before) self.connect_after('key-press-event', self.key_press_event_cb_after)
def delete_event_cb(window, event, app): return app.quit()