magic_card_spider.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/10/31 13:48
  5. import inspect
  6. import requests
  7. import user_agent
  8. from loguru import logger
  9. from parsel import Selector
  10. from mysql_pool import MySQLConnectionPool
  11. from tenacity import retry, stop_after_attempt, wait_fixed
  12. from settings import LANGUAGE_LIST
  13. """
  14. https://gatherer.wizards.com/advanced-search
  15. """
  16. logger.remove()
  17. logger.add("./logs/{time:YYYYMMDD}.log", encoding='utf-8', rotation="00:00",
  18. format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}",
  19. level="DEBUG", retention="7 day")
  20. headers = {
  21. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  22. # "referer": "https://gatherer.wizards.com/M20/en-us/1/aerial-assault",
  23. "user-agent": user_agent.generate_user_agent()
  24. }
  25. def after_log(retry_state):
  26. """
  27. retry 回调
  28. :param retry_state: RetryCallState 对象
  29. """
  30. # 检查 args 是否存在且不为空
  31. if retry_state.args and len(retry_state.args) > 0:
  32. log = retry_state.args[0] # 获取传入的 logger
  33. else:
  34. log = logger # 使用全局 logger
  35. if retry_state.outcome.failed:
  36. log.warning(
  37. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  38. else:
  39. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  40. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  41. def get_proxys(log):
  42. """
  43. 获取代理
  44. :return: 代理
  45. """
  46. tunnel = "x371.kdltps.com:15818"
  47. kdl_username = "t13753103189895"
  48. kdl_password = "o0yefv6z"
  49. try:
  50. proxies = {
  51. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel},
  52. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel}
  53. }
  54. return proxies
  55. except Exception as e:
  56. log.error(f"Error getting proxy: {e}")
  57. raise e
  58. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  59. def get_cards_single_page(log, sql_pool, card_lang_url):
  60. """
  61. 获取卡组列表 单页信息
  62. :param log: logger对象
  63. :param sql_pool: MySQL对象
  64. :param card_lang_url: 单页链接
  65. :return: len(tag_div_list) -> 控制翻页
  66. """
  67. log.debug(f" ------------------------- 当前查询的 card_lang_url 为:{card_lang_url} -------------------------")
  68. response = requests.get(card_lang_url, headers=headers, timeout=5)
  69. # response = requests.get(card_list_url, headers=headers, proxies=get_proxys(log))
  70. response.raise_for_status()
  71. selector = Selector(response.text)
  72. tag_div_list = selector.xpath(
  73. '//div[@data-testid="resultsListWrapper"]/div') # data-testid="resultsListWrapper"
  74. for tag_div in tag_div_list:
  75. # card_name = tag_div.xpath('./div[@data-testid="cardName"]/a/text()').get()
  76. card_detail_url = tag_div.xpath('./a/@href').get()
  77. if card_detail_url:
  78. card_detail_url = "https://gatherer.wizards.com" + card_detail_url
  79. try:
  80. get_card_detail(log, sql_pool, card_detail_url)
  81. except Exception as e:
  82. log.error(f"Error getting card detail: {e}")
  83. else:
  84. log.warning(f"Warning getting card detail: {card_detail_url}")
  85. return len(tag_div_list)
  86. def get_cards_list(log, sql_pool, card_lang_url):
  87. """
  88. card 列表 翻页 每页72条
  89. https://gatherer.wizards.com/sets/SPM?page=2
  90. :param log: logger对象
  91. :param sql_pool: MySQL对象
  92. :param card_lang_url: 翻页链接
  93. """
  94. log.debug('开始查询卡组信息 ->->->->->->->->->->->->->->->->->->->')
  95. for page in range(1, 1000):
  96. card_list_url = f"{card_lang_url}{page}"
  97. log.debug(f" ------------------------- 当前查询的页码为:{page} -------------------------")
  98. len_tag_div_list = get_cards_single_page(log, sql_pool, card_list_url)
  99. if len_tag_div_list < 72:
  100. log.debug(f"当前页为 {page}, 当页卡牌数量为 {len_tag_div_list}, 没有更多数据了.........")
  101. break
  102. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  103. def get_card_detail(log, sql_pool, card_detail_url):
  104. """
  105. 卡牌详情
  106. :param log: logger对象
  107. :param sql_pool: MySQL对象
  108. :param card_detail_url: 详情页链接
  109. """
  110. log.debug('开始查询卡牌 <详情> 信息 ->->->->->->->->->->->->->->->->->->->')
  111. response = requests.get(card_detail_url, headers=headers)
  112. response.raise_for_status()
  113. selector = Selector(response.text)
  114. tag_detail_section = selector.xpath('//section[@data-testid="cardDetailsWrapper"]')
  115. card_name = tag_detail_section.xpath('.//h1[@data-testid="cardDetailsCardName"]/text()').get()
  116. card_type = tag_detail_section.xpath('.//h1[@data-testid="cardDetailsTypeLine"]/text()').get()
  117. card_rarity = tag_detail_section.xpath('.//h1[@data-testid="cardDetailsRarity"]/text()').get()
  118. card_artist = tag_detail_section.xpath('./article[3]/div[1]/div[1]/section//h1/text()').get() # 作者
  119. card_p_t = tag_detail_section.xpath('./article[3]/div[1]/div[2]/section/section/div//text()').getall()
  120. card_p_t = "".join(card_p_t).strip() if card_p_t else None
  121. card_set = tag_detail_section.xpath('./article[3]/div[2]/div[1]/section/a/h1//text()').getall() # 卡组
  122. card_set = "".join(card_set).strip() if card_set else None
  123. card_number = tag_detail_section.xpath('.//h1[@data-testid="cardDetailsCardNumber"]/text()').get() # 编号
  124. card_language = tag_detail_section.xpath('.//h1[@data-testid="cardDetailsLanguage"]/text()').get()
  125. img = selector.xpath('//img[@data-testid="cardFrontImage"]/@src').get()
  126. if 'webp' in img:
  127. img = img.replace('webp', 'png')
  128. detail_data_dict = {
  129. "card_name": card_name,
  130. "card_type": card_type,
  131. "card_rarity": card_rarity,
  132. "card_artist": card_artist,
  133. "card_p_t": card_p_t,
  134. "card_set": card_set,
  135. "card_number": card_number,
  136. "card_language": card_language,
  137. "card_url": card_detail_url,
  138. "img": img
  139. }
  140. # print(detail_data_dict)
  141. # 更新数据
  142. sql_pool.insert_one_or_dict(table="magic_cards_record", data=detail_data_dict, ignore=True)
  143. @retry(stop=stop_after_attempt(100), wait=wait_fixed(3600), after=after_log)
  144. def magic_main(log):
  145. """
  146. 主函数
  147. :param log: logger对象
  148. """
  149. log.info(
  150. f'开始运行 {inspect.currentframe().f_code.co_name} 爬虫任务....................................................')
  151. # 配置 MySQL 连接池
  152. sql_pool = MySQLConnectionPool(log=log)
  153. if not sql_pool.check_pool_health():
  154. log.error("数据库连接池异常")
  155. raise RuntimeError("数据库连接池异常")
  156. try:
  157. # 获取所有卡组中的卡牌信息
  158. for card_lang_url in LANGUAGE_LIST:
  159. try:
  160. get_cards_list(log, sql_pool, card_lang_url)
  161. except Exception as e:
  162. log.error(f"Error get_cards: {e}")
  163. except Exception as e:
  164. log.error(f'{inspect.currentframe().f_code.co_name} error: {e}')
  165. finally:
  166. log.info(f'爬虫程序 {inspect.currentframe().f_code.co_name} 运行结束,等待下一轮的采集任务............')
  167. if __name__ == '__main__':
  168. # card_url_ = "https://gatherer.wizards.com/sets/SPM"
  169. # https://gatherer.wizards.com/SPE/en-us/1/amateur-hero
  170. # get_card_detail(logger, None, "https://gatherer.wizards.com/MKM/zh-cn/167/a-killer-among-us")
  171. magic_main(logger)