parser.py 2.1 KB

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