parser.py 2.1 KB

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