spider.py 7.0 KB

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