parser.py 2.2 KB

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