parser.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/python3
  2. import threading
  3. from queue import Queue
  4. from db import db
  5. from source import Source
  6. from linklist import LinkList
  7. from news import News
  8. from paid_parser import PaidParser
  9. from time import strftime
  10. import sys
  11. def parseSource(s):
  12. global q
  13. q = Queue()
  14. num_worker_threads = 10
  15. sel = None
  16. rss = False
  17. if "selector" in s:
  18. sel = s["selector"]
  19. if "rss" in s:
  20. rss = bool(s["rss"])
  21. l = LinkList(s["link"], sel, rss=rss)
  22. kw = d.get_keywords(s["category"])
  23. # print(kw)
  24. if l is not None:
  25. for a in l.links:
  26. if not d.article_exists(a.lower()):
  27. q.put(a)
  28. print("[%s][Source] %s: %d/%d new/total articles" %
  29. (strftime("%H:%M:%S"), s["name"], q.qsize(), len(l.links)))
  30. if not q.empty():
  31. num_worker_threads = min(10, q.qsize())
  32. threads = []
  33. for i in range(num_worker_threads):
  34. t = threading.Thread(target=news_worker, args=[s, kw])
  35. t.daemon = True
  36. t.start()
  37. threads.append(t)
  38. # print("Waiting for %d queue elements" % q.qsize())
  39. q.join() # block until all tasks are done
  40. # print("Finished waiting for the queue")
  41. for i in range(num_worker_threads):
  42. q.put(None)
  43. for t in threads:
  44. t.join(10)
  45. # print("[Source] %s => Finished parsing" %s["name"])
  46. def news_worker(source, kw):
  47. source_id = source["_id"]
  48. source_name = source["name"]
  49. source_category = source["category"]
  50. paid = False
  51. if "paid" in source and source["paid"]:
  52. paid = True
  53. tname = threading.current_thread().name
  54. while True:
  55. try:
  56. item = q.get(timeout=5)
  57. except:
  58. #print("Failed to get item")
  59. q.task_done()
  60. break
  61. if item is None:
  62. q.task_done()
  63. break
  64. #print("[Thread %s] %s" % (tname,item))
  65. try:
  66. html = None
  67. if paid:
  68. p = PaidParser(item)
  69. html = p.html
  70. n = News(item, source_id, source_name,
  71. source_category, kw, html=html)
  72. #print("[Thread %s] Finished" % tname)
  73. d.insert_article(n.get())
  74. except Exception as e:
  75. print("#### EXCEPTION ########")
  76. print(e)
  77. print(item)
  78. print("whut")
  79. print("#### END EXCEPTION ####")
  80. finally:
  81. q.task_done()
  82. q = Queue()
  83. d = db()
  84. d.purge_error()
  85. for s in d.sources():
  86. parseSource(s)
  87. sys.stdout.flush()
  88. print("###############################################################################")