utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. from HTMLParser import HTMLParser
  2. #import htmlentitydefs
  3. import csv
  4. from codecs import getincrementalencoder
  5. import cStringIO
  6. import re
  7. from random import choice
  8. ua_versions = ('26.0', '27.0', '28.0')
  9. ua_os = ('Windows NT 6.3; WOW64',
  10. 'X11; Linux x86_64',
  11. 'X11; Linux x86')
  12. ua = "Mozilla/5.0 ({os}) Gecko/20100101 Firefox/{version}"
  13. def gen_useragent():
  14. # TODO
  15. return ua.format(os=choice(ua_os), version=choice(ua_versions))
  16. def highlight_content(content, query):
  17. if not content:
  18. return None
  19. # ignoring html contents
  20. # TODO better html content detection
  21. if content.find('<') != -1:
  22. return content
  23. query = query.decode('utf-8')
  24. if content.lower().find(query.lower()) > -1:
  25. query_regex = u'({0})'.format(re.escape(query))
  26. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  27. content, flags=re.I | re.U)
  28. else:
  29. regex_parts = []
  30. for chunk in query.split():
  31. if len(chunk) == 1:
  32. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  33. else:
  34. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  35. query_regex = u'({0})'.format('|'.join(regex_parts))
  36. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  37. content, flags=re.I | re.U)
  38. return content
  39. class HTMLTextExtractor(HTMLParser):
  40. def __init__(self):
  41. HTMLParser.__init__(self)
  42. self.result = []
  43. def handle_data(self, d):
  44. self.result.append(d)
  45. def handle_charref(self, number):
  46. if number[0] in (u'x', u'X'):
  47. codepoint = int(number[1:], 16)
  48. else:
  49. codepoint = int(number)
  50. self.result.append(unichr(codepoint))
  51. def handle_entityref(self, name):
  52. #codepoint = htmlentitydefs.name2codepoint[name]
  53. #self.result.append(unichr(codepoint))
  54. self.result.append(name)
  55. def get_text(self):
  56. return u''.join(self.result)
  57. def html_to_text(html):
  58. s = HTMLTextExtractor()
  59. s.feed(html)
  60. return s.get_text()
  61. class UnicodeWriter:
  62. """
  63. A CSV writer which will write rows to CSV file "f",
  64. which is encoded in the given encoding.
  65. """
  66. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  67. # Redirect output to a queue
  68. self.queue = cStringIO.StringIO()
  69. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  70. self.stream = f
  71. self.encoder = getincrementalencoder(encoding)()
  72. def writerow(self, row):
  73. unicode_row = []
  74. for col in row:
  75. if type(col) == str or type(col) == unicode:
  76. unicode_row.append(col.encode('utf-8').strip())
  77. else:
  78. unicode_row.append(col)
  79. self.writer.writerow(unicode_row)
  80. # Fetch UTF-8 output from the queue ...
  81. data = self.queue.getvalue()
  82. data = data.decode("utf-8")
  83. # ... and reencode it into the target encoding
  84. data = self.encoder.encode(data)
  85. # write to the target stream
  86. self.stream.write(data)
  87. # empty queue
  88. self.queue.truncate(0)
  89. def writerows(self, rows):
  90. for row in rows:
  91. self.writerow(row)