spider.py 7.0 KB

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