weixin_account_crawler.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. """
  2. @author: luojunhui
  3. """
  4. import time
  5. import traceback
  6. from typing import List, Set, Dict, Tuple
  7. from tqdm import tqdm
  8. from pymysql.cursors import DictCursor
  9. from applications import WeixinSpider, longArticlesMySQL, log, bot, aiditApi
  10. from applications.const import WeixinVideoCrawlerConst
  11. from applications.functions import Functions
  12. const = WeixinVideoCrawlerConst()
  13. function = Functions()
  14. def get_inner_account_gh_id() -> Set[str]:
  15. """
  16. 获取内部账号名称
  17. :return:
  18. """
  19. accounts = aiditApi.get_publish_account_from_aigc()
  20. gh_id_list = [i['ghId'] for i in accounts]
  21. return set(gh_id_list)
  22. class WeixinAccountCrawler(object):
  23. """
  24. 账号抓取
  25. """
  26. def __init__(self):
  27. self.db_client = longArticlesMySQL()
  28. self.spider = WeixinSpider()
  29. self.crawler_account_count = 0
  30. def get_crawler_articles(self) -> List[Dict]:
  31. """
  32. 获取已经抓取到的文章,判断其是否有链接账号,若有则继续抓账号
  33. :return:
  34. """
  35. sql = f"""
  36. SELECT id, article_url
  37. FROM publish_single_video_source
  38. WHERE source_account = {const.NEED_SCAN_SOURCE_ACCOUNT};
  39. """
  40. article_url_list = self.db_client.select(sql, cursor_type=DictCursor)
  41. return article_url_list
  42. def update_crawler_article_status(self, article_id_tuple: Tuple[int, ...]) -> int:
  43. """
  44. :param article_id_tuple:
  45. :return:
  46. """
  47. sql = """
  48. UPDATE publish_single_video_source
  49. SET source_account = %s
  50. WHERE id IN %s;
  51. """
  52. affected_rows = self.db_client.update(sql, (const.DO_NOT_NEED_SOURCE_ACCOUNT, article_id_tuple))
  53. return affected_rows
  54. def get_seed_titles(self, run_date) -> List[str]:
  55. """
  56. :return:
  57. """
  58. publish_timestamp_threshold = int(run_date.timestamp()) - const.STAT_PERIOD
  59. sql = f"""
  60. SELECT distinct title
  61. FROM datastat_sort_strategy
  62. WHERE read_rate > {const.READ_AVG_MULTIPLE} and view_count > {const.MIN_READ_COUNT} and publish_timestamp > {publish_timestamp_threshold}
  63. ORDER BY read_rate DESC;
  64. """
  65. title_list = self.db_client.select(sql, cursor_type=DictCursor)
  66. title_list = [i['title'] for i in title_list]
  67. return title_list
  68. def is_original(self, article_url: str) -> bool:
  69. """
  70. 判断视频是否是原创
  71. :return:
  72. """
  73. response = self.spider.get_article_text(article_url)
  74. data = response['data']['data']
  75. return data['is_original']
  76. def insert_account(self, gh_id: str, account_name: str) -> int:
  77. """
  78. 插入账号
  79. :param account_name:
  80. :param gh_id:
  81. :return:
  82. """
  83. init_date = time.strftime("%Y-%m-%d", time.localtime())
  84. sql = """
  85. INSERT IGNORE INTO weixin_account_for_videos
  86. (gh_id, account_name, account_init_date)
  87. VALUES
  88. (%s, %s, %s);
  89. """
  90. insert_rows = self.db_client.update(sql, (gh_id, account_name, init_date))
  91. return insert_rows
  92. def process_search_result(self, response: Dict, inner_account_set: Set[str]):
  93. """
  94. 处理搜索结果
  95. :param response:
  96. :param inner_account_set:
  97. :return:
  98. """
  99. if response['code'] != const.REQUEST_SUCCESS:
  100. return
  101. article_list = response['data']['data']
  102. if article_list:
  103. for article in article_list:
  104. try:
  105. # 先判断账号是否内部账号
  106. article_url = article['url']
  107. account_detail = self.spider.get_account_by_url(article_url)
  108. account_detail = account_detail['data']['data']
  109. account_name = account_detail['account_name']
  110. gh_id = account_detail['wx_gh']
  111. if gh_id in inner_account_set:
  112. continue
  113. # 判断搜索结果是否原创
  114. if self.is_original(article_url):
  115. continue
  116. # 判断是否有视频链接
  117. try:
  118. video_url = function.get_video_url(article_url)
  119. except Exception as e:
  120. continue
  121. if not video_url:
  122. continue
  123. # 将账号抓取进来
  124. insert_rows = self.insert_account(gh_id=gh_id, account_name=account_name)
  125. if insert_rows:
  126. log(
  127. task="account_crawler_v1",
  128. function="process_search_result",
  129. message="insert account success",
  130. data={
  131. "gh_id": gh_id,
  132. "account_name": account_name
  133. }
  134. )
  135. self.crawler_account_count += 1
  136. except Exception as e:
  137. log(
  138. task="account_crawler_v1",
  139. function="process_search_result",
  140. message="insert account error",
  141. data={
  142. "error": str(e),
  143. "traceback": traceback.format_exc(),
  144. "data": article
  145. }
  146. )
  147. def search_title_in_weixin(self, title: str, inner_account_set: Set[str]) -> None:
  148. """
  149. 调用搜索接口,在微信搜索
  150. :param inner_account_set:
  151. :param title:
  152. :return:
  153. """
  154. for page_index in tqdm(range(1, const.MAX_SEARCH_PAGE_NUM + 1), desc='searching: {}'.format(title)):
  155. try:
  156. response = self.spider.search_articles(title, page=str(page_index))
  157. self.process_search_result(response, inner_account_set)
  158. time.sleep(const.SLEEP_SECONDS)
  159. except Exception as e:
  160. log(
  161. task="account_crawler_v1",
  162. function="search_title_in_weixin",
  163. message="search title error",
  164. data={
  165. "error": str(e),
  166. "traceback": traceback.format_exc(),
  167. "title": title
  168. }
  169. )
  170. def run(self, run_date) -> None:
  171. """
  172. 入口函数
  173. :return:
  174. """
  175. # get seed titles
  176. title_list = self.get_seed_titles(run_date)
  177. # get inner accounts set
  178. inner_account_gh_id_set = get_inner_account_gh_id()
  179. start_time = time.time()
  180. for title in tqdm(title_list, desc="search each title"):
  181. self.search_title_in_weixin(title, inner_account_gh_id_set)
  182. # 通知
  183. bot(
  184. title="微信账号抓取V1完成",
  185. detail={
  186. "总更新账号数量": self.crawler_account_count,
  187. "总耗时": time.time() - start_time,
  188. "种子标题数量": len(title_list)
  189. },
  190. mention=False
  191. )
  192. def run_v2(self) -> None:
  193. """
  194. 入口函数
  195. :return:
  196. """
  197. # get article list
  198. crawler_article_list = self.get_crawler_articles()
  199. article_id_list = []
  200. insert_account_count = 0
  201. for crawler_article_obj in tqdm(crawler_article_list, desc="crawler article list"):
  202. try:
  203. article_id = crawler_article_obj['id']
  204. # 记录处理过的id
  205. article_id_list.append(int(article_id))
  206. article_url = crawler_article_obj['article_url']
  207. # 判断文章是否原创
  208. if self.is_original(article_url):
  209. continue
  210. try:
  211. source_account_info = function.get_source_account(article_url)
  212. except Exception as e:
  213. continue
  214. if not source_account_info:
  215. continue
  216. if source_account_info:
  217. account_name = source_account_info['name']
  218. gh_id = source_account_info['gh_id']
  219. affected_rows = self.insert_account(gh_id=gh_id, account_name=account_name)
  220. insert_account_count += affected_rows
  221. else:
  222. continue
  223. except Exception as e:
  224. print(e)
  225. print(traceback.format_exc())
  226. if article_id_list:
  227. article_id_tuple = tuple(article_id_list)
  228. affected_rows = self.update_crawler_article_status(article_id_tuple)
  229. bot(
  230. title="微信账号抓取V2完成",
  231. detail={
  232. "扫描文章数量": len(crawler_article_list),
  233. "新增账号数量": insert_account_count
  234. },
  235. mention=False
  236. )