spider.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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():
  68. if quit_flag is True:
  69. break
  70. url = data["url"]
  71. corpusid = data["corpusid"]
  72. if 'consumed' in data.keys() and data['consumed'] is True:
  73. print(corpusid, "already inserted")
  74. continue
  75. # print(data['corpusid'])
  76. # print(data['url'])
  77. print('add {} to the task queue'.format(corpusid))
  78. q.put((url, corpusid))
  79. #
  80. print("Waitting for the task queue to complete...")
  81. q.join()
  82. print("The task queue has been completed!")
  83. # 停止线程
  84. for i in range(NUM_THREADS):
  85. q.put(None)
  86. for t in threads:
  87. print("stoping worker: {}" . format(t.native_id))
  88. t.join()
  89. def mark_data_as_consumed(corpus_id):
  90. result = papers.update_one({'corpusid': corpus_id}, {
  91. '$set': {'consumed': True}})
  92. def worker(q):
  93. while True:
  94. item = q.get()
  95. if item is None:
  96. break
  97. url = urlparse(item[0]).path
  98. paper_id = url.split('/')[-1]
  99. corpus_id = item[1]
  100. print('crawling {} data: {}'.format(corpus_id, url))
  101. try:
  102. data = fetch_data(paper_id)
  103. if data is not None:
  104. # papers_data.insert_one(data)
  105. filter = {'corpusId': corpus_id}
  106. update = {'$set': data}
  107. result = papers_data.update_one(filter, update, upsert=True)
  108. mark_data_as_consumed(corpus_id)
  109. print(result.upserted_id, "inserted successfully")
  110. except Exception as error:
  111. # handle the exception
  112. print("An exception occurred:", error)
  113. finally:
  114. q.task_done()
  115. def get_paper(paper_id):
  116. rsp = requests.get(f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}',
  117. headers={'x-api-key': S2_API_KEY},
  118. params={'fields': QUERY_FIELDS1})
  119. rsp.raise_for_status()
  120. return rsp.json()
  121. def get_citations(paper_id):
  122. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/citations',
  123. headers={'x-api-key': S2_API_KEY},
  124. params={'fields': QUERY_FIELDS2})
  125. return list(edge['citingPaper'] for edge in edges)
  126. def get_references(paper_id):
  127. edges = get_citation_edges(url=f'https://api.semanticscholar.org/graph/v1/paper/{paper_id}/references',
  128. headers={'x-api-key': S2_API_KEY},
  129. params={'fields': QUERY_FIELDS2})
  130. return list(edge['citedPaper'] for edge in edges)
  131. # 接口存在人机验证
  132. def get_related_pages(paper_id):
  133. rsp = requests.get(url=f'https://www.semanticscholar.org/api/1/paper/{paper_id}/related-papers?limit=10&recommenderType=relatedPapers',
  134. headers={'x-api-key': S2_API_KEY},
  135. params={'fields': QUERY_FIELDS3})
  136. rsp.raise_for_status()
  137. return rsp.json()['papers']
  138. def get_recommender_pages(paper_id):
  139. rsp = requests.get(url=f'https://api.semanticscholar.org/recommendations/v1/papers/forpaper/{paper_id}',
  140. headers={'x-api-key': S2_API_KEY},
  141. params={'fields': QUERY_FIELDS2})
  142. rsp.raise_for_status()
  143. return rsp.json()['recommendedPapers']
  144. def get_citation_edges(**req_kwargs):
  145. """This helps with API endpoints that involve paging."""
  146. page_size = 1000
  147. offset = 0
  148. while True:
  149. req_kwargs.setdefault('params', dict())
  150. req_kwargs['params']['limit'] = page_size
  151. req_kwargs['params']['offset'] = offset
  152. rsp = requests.get(**req_kwargs)
  153. rsp.raise_for_status()
  154. page = rsp.json()["data"]
  155. for element in page:
  156. yield element
  157. if len(page) < page_size:
  158. break # no more pages
  159. offset += page_size
  160. def fetch_data(paper_id):
  161. print("fetching data:", paper_id)
  162. data = get_paper(paper_id)
  163. # print(paper)
  164. data['citations'] = get_citations(paper_id)
  165. data['references'] = get_references(paper_id)
  166. data['recommenderPages'] = get_recommender_pages(paper_id)
  167. return data if isinstance(data, dict) else None
  168. def onSigInt(signo, frame):
  169. global quit_flag
  170. quit_flag = True
  171. print('Ctrl C: Waiting for the process to exit...')
  172. if __name__ == "__main__":
  173. # 主进程退出信号
  174. signal.signal(signal.SIGINT, onSigInt)
  175. parser = argparse.ArgumentParser(description="Crawl data from URLs")
  176. parser.add_argument(
  177. "command", choices=["add_paper", "crawl_data"], help="Command to execute"
  178. )
  179. parser.add_argument("--path", help="Path to add to papers")
  180. args = parser.parse_args()
  181. if args.command == "add_paper":
  182. add_paper(args.path)
  183. elif args.command == "crawl_data":
  184. crawl_data()