parser.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. def parseSource(s):
  10. global q
  11. q=Queue()
  12. num_worker_threads=10
  13. sel=None
  14. rss=False
  15. if "selector" in s:
  16. sel=s["selector"]
  17. if "rss" in s:
  18. rss=bool(s["rss"])
  19. l=LinkList(s["link"],sel,rss=rss)
  20. kw=d.get_keywords(s["category"])
  21. # print(kw)
  22. if l is not None:
  23. for a in l.links:
  24. if not d.article_exists(a):
  25. q.put(a)
  26. print("[Source] %s: %d/%d new/total articles" % ( s["name"], q.qsize(), len(l.links)))
  27. if not q.empty():
  28. num_worker_threads=min(10,q.qsize())
  29. threads=[]
  30. for i in range(num_worker_threads):
  31. t = threading.Thread(target=news_worker,args=[s,kw])
  32. t.daemon=True
  33. t.start()
  34. threads.append(t)
  35. # print("Waiting for %d queue elements" % q.qsize())
  36. q.join() #block until all tasks are done
  37. # print("Finished waiting for the queue")
  38. for i in range(num_worker_threads):
  39. q.put(None)
  40. for t in threads:
  41. t.join(10)
  42. # print("[Source] %s => Finished parsing" %s["name"])
  43. def news_worker(source,kw):
  44. source_id=source["_id"]
  45. source_name=source["name"]
  46. paid=False
  47. if "paid" in source and source["paid"]:
  48. paid=True
  49. tname=threading.current_thread().name
  50. while True:
  51. try:
  52. item = q.get(timeout=5)
  53. except:
  54. print("Failed to get item")
  55. q.task_done()
  56. break
  57. if item is None:
  58. q.task_done()
  59. break
  60. print("[Thread %s] %s" % (tname,item))
  61. try:
  62. html=None
  63. if paid:
  64. p=PaidParser(item)
  65. html=p.html
  66. n=News(item,source_id,source_name,kw,html=html)
  67. print("[Thread %s] Finished" % tname)
  68. d.insert_article(n.get())
  69. except Exception as e:
  70. print(e)
  71. print("whut")
  72. finally:
  73. q.task_done()
  74. q=Queue()
  75. d=db()
  76. d.purge_error()
  77. for s in d.sources():
  78. parseSource(s)