parser.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. source_category=source["category"]
  47. paid=False
  48. if "paid" in source and source["paid"]:
  49. paid=True
  50. tname=threading.current_thread().name
  51. while True:
  52. try:
  53. item = q.get(timeout=5)
  54. except:
  55. #print("Failed to get item")
  56. q.task_done()
  57. break
  58. if item is None:
  59. q.task_done()
  60. break
  61. print("[Thread %s] %s" % (tname,item))
  62. try:
  63. html=None
  64. if paid:
  65. p=PaidParser(item)
  66. html=p.html
  67. n=News(item,source_id,source_name,source_category,kw,html=html)
  68. print("[Thread %s] Finished" % tname)
  69. d.insert_article(n.get())
  70. except Exception as e:
  71. print(e)
  72. print("whut")
  73. finally:
  74. q.task_done()
  75. q=Queue()
  76. d=db()
  77. d.purge_error()
  78. for s in d.sources():
  79. parseSource(s)