spider.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. sub_list = []
  47. for line in data_list:
  48. sub_list.append(line)
  49. if len(sub_list) == 2000:
  50. result = papers.insert_many(sub_list, ordered=False)
  51. inserted_ids += len(result.inserted_ids)
  52. sub_list = []
  53. if sub_list:
  54. result = papers.insert_many(sub_list, ordered=False)
  55. inserted_ids += len(result.inserted_ids)
  56. sub_list = []
  57. print('-------process', inserted_ids, '/', len(data_list))
  58. except pymongo.errors.BulkWriteError as e:
  59. inserted_ids = e.details['nInserted']
  60. finally:
  61. # 输出插入结果
  62. print("总插入数据: {0}, 已插入数据: {1}, 已存在数据: {2}" .format(
  63. len(data_list), inserted_ids, papers.count_documents({})))
  64. def crawl_data():
  65. papers_data.create_index("corpusId", unique=True)
  66. # 创建任务队列和线程
  67. q = Queue(TASK_QUEUE_LEN)
  68. # num_threads = 4
  69. threads = []
  70. for i in range(NUM_THREADS):
  71. t = Thread(target=worker, args=(q,))
  72. t.daemon = True
  73. t.start()
  74. print("starting worker: {}".format(t.native_id))
  75. threads.append(t)
  76. # 从数据库中读取 URL,加入任务队列
  77. for data in papers.find({'$or': [{'consumed': {'$exists': False}}, {'consumed': False}]}):
  78. if quit_flag:
  79. break
  80. if 'consumed' in data and data['consumed']:
  81. print(data['corpusid'], "already inserted")
  82. continue
  83. print('add {} to the task queue'.format(data['corpusid']))
  84. q.put((data['url'], data['corpusid']))
  85. #
  86. print("Waitting for the task queue to complete...")
  87. q.join()
  88. print("The task queue has been completed!")
  89. # 停止线程
  90. for i in range(NUM_THREADS):
  91. q.put(None)
  92. for t in threads:
  93. print("stoping worker: {}" . format(t.native_id))
  94. t.join()
  95. def mark_data_as_consumed(corpus_id):
  96. result = papers.update_one({'corpusid': corpus_id}, {
  97. '$set': {'consumed': True}})
  98. def worker(q):
  99. while True:
  100. item = q.get()
  101. if item is None:
  102. break
  103. url = urlparse(item[0]).path
  104. paper_id = url.split('/')[-1]
  105. corpus_id = item[1]
  106. print('crawling {} data: {}'.format(corpus_id, url))
  107. try:
  108. data = fetch_data(paper_id)
  109. if data is not None:
  110. # papers_data.insert_one(data)
  111. filter = {'corpusId': corpus_id}
  112. update = {'$set': data}
  113. result = papers_data.update_one(filter, update, upsert=True)
  114. mark_data_as_consumed(corpus_id)
  115. print(result.upserted_id, "inserted successfully")
  116. except Exception as error:
  117. # handle the exception
  118. print("An exception occurred:", error)
  119. finally:
  120. q.task_done()
  121. def get_paper(paper_id):
  122. rsp = requests.get(f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}',
  123. headers={'x-api-key': S2_API_KEY},
  124. params={'fields': QUERY_FIELDS1})
  125. rsp.raise_for_status()
  126. return rsp.json()
  127. def get_citations(paper_id):
  128. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/citations',
  129. headers={'x-api-key': S2_API_KEY},
  130. params={'fields': QUERY_FIELDS2})
  131. return list(edge['citingPaper'] for edge in edges)
  132. def get_references(paper_id):
  133. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/references',
  134. headers={'x-api-key': S2_API_KEY},
  135. params={'fields': QUERY_FIELDS2})
  136. return list(edge['citedPaper'] for edge in edges)
  137. # 接口存在人机验证
  138. def get_related_papers(paper_id):
  139. rsp = requests.get(url=f'https://www.semanticscholar.org/api/1/paper/{paper_id}/related-papers?limit=10&recommenderType=relatedPapers',
  140. headers={'x-api-key': S2_API_KEY},
  141. params={'fields': QUERY_FIELDS3})
  142. rsp.raise_for_status()
  143. return rsp.json()['papers']
  144. def get_recommended_papers(paper_id):
  145. rsp = requests.get(url=f'https://api.semanticscholar.org/recommendations/v1/papers/forpaper/{paper_id}',
  146. headers={'x-api-key': S2_API_KEY},
  147. params={'fields': QUERY_FIELDS2})
  148. rsp.raise_for_status()
  149. return rsp.json()['recommendedPapers']
  150. def get_citation_edges(**req_kwargs):
  151. """This helps with API endpoints that involve paging."""
  152. page_size = 1000
  153. offset = 0
  154. while True:
  155. req_kwargs.setdefault('params', dict())
  156. req_kwargs['params']['limit'] = page_size
  157. req_kwargs['params']['offset'] = offset
  158. rsp = requests.get(**req_kwargs)
  159. rsp.raise_for_status()
  160. page = rsp.json()["data"]
  161. for element in page:
  162. yield element
  163. if len(page) < page_size:
  164. break # no more pages
  165. offset += page_size
  166. def fetch_data(paper_id):
  167. print("fetching data:", paper_id)
  168. data = get_paper(paper_id)
  169. # print(paper)
  170. data['citations'] = get_citations(paper_id)
  171. data['references'] = get_references(paper_id)
  172. data['recommendedPapers'] = get_recommended_papers(paper_id)
  173. return data if isinstance(data, dict) else None
  174. def onSigInt(signo, frame):
  175. global quit_flag
  176. quit_flag = True
  177. print('Ctrl C: Waiting for the process to exit...')
  178. if __name__ == "__main__":
  179. # 主进程退出信号
  180. signal.signal(signal.SIGINT, onSigInt)
  181. parser = argparse.ArgumentParser(description="Crawl data from URLs")
  182. parser.add_argument(
  183. "command", choices=["add_paper", "crawl_data"], help="Command to execute"
  184. )
  185. parser.add_argument("--path", help="Path to add to papers")
  186. args = parser.parse_args()
  187. if args.command == "add_paper":
  188. add_paper(args.path)
  189. elif args.command == "crawl_data":
  190. crawl_data()