spider.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import requests
  2. import os
  3. import signal
  4. import argparse
  5. import json
  6. import pymongo
  7. from queue import Queue
  8. from threading import Thread
  9. from urllib.parse import urlparse
  10. # S2_API_KEY = os.getenv('S2_API_KEY')
  11. QUERY_FIELDS1 = 'paperId,corpusId,title,authors,year,url,tldr,venue,externalIds,fieldsOfStudy,s2FieldsOfStudy,abstract,citationCount,referenceCount,publicationTypes,influentialCitationCount,publicationDate,journal'
  12. QUERY_FIELDS2 = 'paperId,corpusId,title,authors,year,url,venue,externalIds,fieldsOfStudy,s2FieldsOfStudy,abstract,citationCount,referenceCount,publicationTypes,influentialCitationCount,publicationDate,journal'
  13. QUERY_FIELDS3 = 'paperId,corpusId,title,authors'
  14. # 读取配置文件中的数据库参数
  15. with open("config.json", "r") as f:
  16. config = json.load(f)
  17. db_url = config["db_url"]
  18. db_name = config["db_name"]
  19. db_collection = config["db_collection"]
  20. NUM_THREADS = config["num_threads"]
  21. TASK_QUEUE_LEN = config["task_queue_len"]
  22. S2_API_KEY = config["s2_api_key"]
  23. # 定义退出标志
  24. quit_flag = False
  25. # 连接数据库,创建 papers 集合
  26. client = pymongo.MongoClient(db_url)
  27. db = client[db_name]
  28. papers = db[db_collection]
  29. papers_data = db['{}_data'.format(db_collection)]
  30. def read_file(filename):
  31. data_list = []
  32. with open(filename, 'r') as f:
  33. for line in f:
  34. line_dict = json.loads(line)
  35. data_list.append(line_dict)
  36. # 在这里可以对每个字典对象进行操作,例如:
  37. # print(data_dict['key'])
  38. return data_list
  39. def add_paper(file_path):
  40. papers.create_index("corpusid", unique=True)
  41. # 读取 paper 文件,存入数据库
  42. data_list = read_file(file_path)
  43. # 批量插入数据
  44. inserted_ids = 0
  45. try:
  46. result = papers.insert_many(data_list, ordered=False)
  47. inserted_ids = len(result.inserted_ids)
  48. except pymongo.errors.BulkWriteError as e:
  49. inserted_ids = e.details['nInserted']
  50. finally:
  51. # 输出插入结果
  52. print("总插入数据: {0}, 已插入数据: {1}, 已存在数据: {2}" .format(
  53. len(data_list), inserted_ids, papers.count_documents({})))
  54. def crawl_data():
  55. papers_data.create_index("corpusId", unique=True)
  56. # 创建任务队列和线程
  57. q = Queue(TASK_QUEUE_LEN)
  58. # num_threads = 4
  59. threads = []
  60. for i in range(NUM_THREADS):
  61. t = Thread(target=worker, args=(q,))
  62. t.daemon = True
  63. t.start()
  64. print("starting worker: {}".format(t.native_id))
  65. threads.append(t)
  66. # 从数据库中读取 URL,加入任务队列
  67. for data in papers.find({'$or': [{'consumed': {'$exists': False}}, {'consumed': False}]}):
  68. if quit_flag:
  69. break
  70. if 'consumed' in data and data['consumed']:
  71. print(data['corpusid'], "already inserted")
  72. continue
  73. print('add {} to the task queue'.format(data['corpusid']))
  74. q.put((data['url'], data['corpusid']))
  75. #
  76. print("Waitting for the task queue to complete...")
  77. q.join()
  78. print("The task queue has been completed!")
  79. # 停止线程
  80. for i in range(NUM_THREADS):
  81. q.put(None)
  82. for t in threads:
  83. print("stoping worker: {}" . format(t.native_id))
  84. t.join()
  85. def mark_data_as_consumed(corpus_id):
  86. result = papers.update_one({'corpusid': corpus_id}, {
  87. '$set': {'consumed': True}})
  88. def worker(q):
  89. while True:
  90. item = q.get()
  91. if item is None:
  92. break
  93. url = urlparse(item[0]).path
  94. paper_id = url.split('/')[-1]
  95. corpus_id = item[1]
  96. print('crawling {} data: {}'.format(corpus_id, url))
  97. try:
  98. data = fetch_data(paper_id)
  99. if data is not None:
  100. # papers_data.insert_one(data)
  101. filter = {'corpusId': corpus_id}
  102. update = {'$set': data}
  103. result = papers_data.update_one(filter, update, upsert=True)
  104. mark_data_as_consumed(corpus_id)
  105. print(result.upserted_id, "inserted successfully")
  106. except Exception as error:
  107. # handle the exception
  108. print("An exception occurred:", error)
  109. finally:
  110. q.task_done()
  111. def get_paper(paper_id):
  112. rsp = requests.get(f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}',
  113. headers={'x-api-key': S2_API_KEY},
  114. params={'fields': QUERY_FIELDS1})
  115. rsp.raise_for_status()
  116. return rsp.json()
  117. def get_citations(paper_id):
  118. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/citations',
  119. headers={'x-api-key': S2_API_KEY},
  120. params={'fields': QUERY_FIELDS2})
  121. return list(edge['citingPaper'] for edge in edges)
  122. def get_references(paper_id):
  123. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/references',
  124. headers={'x-api-key': S2_API_KEY},
  125. params={'fields': QUERY_FIELDS2})
  126. return list(edge['citedPaper'] for edge in edges)
  127. # 接口存在人机验证
  128. def get_related_pages(paper_id):
  129. rsp = requests.get(url=f'https://www.semanticscholar.org/api/1/paper/{paper_id}/related-papers?limit=10&recommenderType=relatedPapers',
  130. headers={'x-api-key': S2_API_KEY},
  131. params={'fields': QUERY_FIELDS3})
  132. rsp.raise_for_status()
  133. return rsp.json()['papers']
  134. def get_recommender_pages(paper_id):
  135. rsp = requests.get(url=f'https://api.semanticscholar.org/recommendations/v1/papers/forpaper/{paper_id}',
  136. headers={'x-api-key': S2_API_KEY},
  137. params={'fields': QUERY_FIELDS2})
  138. rsp.raise_for_status()
  139. return rsp.json()['recommendedPapers']
  140. def get_citation_edges(**req_kwargs):
  141. """This helps with API endpoints that involve paging."""
  142. page_size = 1000
  143. offset = 0
  144. while True:
  145. req_kwargs.setdefault('params', dict())
  146. req_kwargs['params']['limit'] = page_size
  147. req_kwargs['params']['offset'] = offset
  148. rsp = requests.get(**req_kwargs)
  149. rsp.raise_for_status()
  150. page = rsp.json()["data"]
  151. for element in page:
  152. yield element
  153. if len(page) < page_size:
  154. break # no more pages
  155. offset += page_size
  156. def fetch_data(paper_id):
  157. print("fetching data:", paper_id)
  158. data = get_paper(paper_id)
  159. # print(paper)
  160. data['citations'] = get_citations(paper_id)
  161. data['references'] = get_references(paper_id)
  162. data['recommenderPages'] = get_recommender_pages(paper_id)
  163. return data if isinstance(data, dict) else None
  164. def onSigInt(signo, frame):
  165. global quit_flag
  166. quit_flag = True
  167. print('Ctrl C: Waiting for the process to exit...')
  168. if __name__ == "__main__":
  169. # 主进程退出信号
  170. signal.signal(signal.SIGINT, onSigInt)
  171. parser = argparse.ArgumentParser(description="Crawl data from URLs")
  172. parser.add_argument(
  173. "command", choices=["add_paper", "crawl_data"], help="Command to execute"
  174. )
  175. parser.add_argument("--path", help="Path to add to papers")
  176. args = parser.parse_args()
  177. if args.command == "add_paper":
  178. add_paper(args.path)
  179. elif args.command == "crawl_data":
  180. crawl_data()