weixin_account_crawler.py 8.7 KB

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