xiaoniangao_plus_get_userid.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. # -*- coding: utf-8 -*-
  2. # @Time: 2023/11/14
  3. import json
  4. import os
  5. import random
  6. import sys
  7. import time
  8. from datetime import date, timedelta
  9. import requests
  10. from appium import webdriver
  11. from appium.webdriver.extensions.android.nativekey import AndroidKey
  12. from bs4 import BeautifulSoup
  13. from selenium.common.exceptions import NoSuchElementException
  14. from selenium.webdriver.common.by import By
  15. import multiprocessing
  16. from common import AliyunLogger
  17. from common.feishu import Feishu
  18. from common.public import clean_title, get_config_from_mysql
  19. sys.path.append(os.getcwd())
  20. from common.common import Common
  21. from common.mq import MQ
  22. from common.scheduling_db import MysqlHelper
  23. def get_redirect_url(url):
  24. res = requests.get(url, allow_redirects=False)
  25. if res.status_code == 302 or res.status_code == 301:
  26. return res.headers['Location']
  27. else:
  28. return url
  29. class XiaoNianGaoPlusRecommend:
  30. env = None
  31. driver = None
  32. log_type = None
  33. def __init__(self, log_type, crawler, env, rule_dict, our_uid):
  34. self.mq = None
  35. self.platform = "小年糕+主页账号ID"
  36. self.download_cnt = 0
  37. self.element_list = []
  38. self.count = 0
  39. self.swipe_count = 0
  40. self.log_type = log_type
  41. self.crawler = crawler
  42. self.env = env
  43. self.rule_dict = rule_dict
  44. self.our_uid = our_uid
  45. if self.env == "dev":
  46. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  47. else:
  48. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  49. Common.logger(self.log_type, self.crawler).info("启动微信")
  50. # 微信的配置文件
  51. caps = {
  52. "platformName": "Android",
  53. "devicesName": "Android",
  54. "appPackage": "com.tencent.mm",
  55. "appActivity": ".ui.LauncherUI",
  56. "autoGrantPermissions": "true",
  57. "noReset": True,
  58. "resetkeyboard": True,
  59. "unicodekeyboard": True,
  60. "showChromedriverLog": True,
  61. "printPageSourceOnFailure": True,
  62. "recreateChromeDriverSessions": True,
  63. "enableWebviewDetailsCollection": True,
  64. "setWebContentsDebuggingEnabled": True,
  65. "newCommandTimeout": 6000,
  66. "automationName": "UiAutomator2",
  67. "chromedriverExecutable": chromedriverExecutable,
  68. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  69. }
  70. self.driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  71. self.driver.implicitly_wait(30)
  72. for i in range(120):
  73. try:
  74. if self.driver.find_elements(By.ID, "com.tencent.mm:id/f2s"):
  75. Common.logger(self.log_type, self.crawler).info("微信启动成功")
  76. break
  77. elif self.driver.find_element(By.ID, "com.android.systemui:id/dismiss_view"):
  78. Common.logger(self.log_type, self.crawler).info("发现并关闭系统下拉菜单")
  79. size = self.driver.get_window_size()
  80. self.driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.8),
  81. int(size['width'] * 0.5), int(size['height'] * 0.2), 200)
  82. else:
  83. pass
  84. except NoSuchElementException:
  85. time.sleep(1)
  86. Common.logger(self.log_type, self.crawler).info("下滑,展示小程序选择面板")
  87. size = self.driver.get_window_size()
  88. self.driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  89. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  90. time.sleep(1)
  91. Common.logger(self.log_type, self.crawler).info('打开小程序"小年糕+"')
  92. self.driver.find_elements(By.XPATH, '//*[@text="小年糕+"]')[-1].click()
  93. time.sleep(5)
  94. self.get_videoList()
  95. time.sleep(1)
  96. self.driver.quit()
  97. def search_elements(self, xpath):
  98. time.sleep(1)
  99. windowHandles = self.driver.window_handles
  100. for handle in windowHandles:
  101. self.driver.switch_to.window(handle)
  102. time.sleep(1)
  103. try:
  104. elements = self.driver.find_elements(By.XPATH, xpath)
  105. if elements:
  106. return elements
  107. except NoSuchElementException:
  108. pass
  109. def check_to_applet(self, xpath):
  110. time.sleep(1)
  111. webViews = self.driver.contexts
  112. self.driver.switch_to.context(webViews[-1])
  113. windowHandles = self.driver.window_handles
  114. for handle in windowHandles:
  115. self.driver.switch_to.window(handle)
  116. time.sleep(1)
  117. try:
  118. self.driver.find_element(By.XPATH, xpath)
  119. Common.logger(self.log_type, self.crawler).info("切换到WebView成功\n")
  120. return
  121. except NoSuchElementException:
  122. time.sleep(1)
  123. def swipe_up(self):
  124. self.search_elements('//*[@class="list-list--list"]')
  125. size = self.driver.get_window_size()
  126. self.driver.swipe(int(size["width"] * 0.5), int(size["height"] * 0.8),
  127. int(size["width"] * 0.5), int(size["height"] * 0.442), 200)
  128. self.swipe_count += 1
  129. def get_video_url(self, video_title_element):
  130. for i in range(3):
  131. self.search_elements('//*[@class="list-list--list"]')
  132. Common.logger(self.log_type, self.crawler).info(f"video_title_element:{video_title_element[0]}")
  133. time.sleep(1)
  134. Common.logger(self.log_type, self.crawler).info("滑动标题至可见状态")
  135. self.driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'});",
  136. video_title_element[0])
  137. time.sleep(3)
  138. Common.logger(self.log_type, self.crawler).info("点击标题")
  139. video_title_element[0].click()
  140. self.check_to_applet(xpath=r'//wx-video[@class="dynamic-index--video-item dynamic-index--video"]')
  141. Common.logger(self.log_type, self.crawler).info("点击标题完成")
  142. time.sleep(10)
  143. video_url_elements = self.search_elements(
  144. '//wx-video[@class="dynamic-index--video-item dynamic-index--video"]')
  145. if video_url_elements:
  146. return video_url_elements[0].get_attribute("src")
  147. def parse_detail(self, index):
  148. page_source = self.driver.page_source
  149. soup = BeautifulSoup(page_source, 'html.parser')
  150. soup.prettify()
  151. video_list = soup.findAll(name="wx-view", attrs={"class": "expose--adapt-parent"})
  152. index = index + 1
  153. element_list = [i for i in video_list][index:]
  154. return element_list[0]
  155. def get_video_info_2(self, video_element):
  156. Common.logger(self.log_type, self.crawler).info(f"本轮已抓取{self.download_cnt}条视频\n")
  157. if self.download_cnt >= int(self.rule_dict.get("videos_cnt", {}).get("min", 10)):
  158. self.count = 0
  159. self.download_cnt = 0
  160. self.element_list = []
  161. return
  162. self.count += 1
  163. Common.logger(self.log_type, self.crawler).info(f"第{self.count}条视频")
  164. # 标题
  165. video_title = video_element.find("wx-view", class_="dynamic--title").text
  166. # 用户名称
  167. user_name = video_element.find("wx-view", class_="dynamic--nick-top").text
  168. video_title_element = self.search_elements(f'//*[contains(text(), "{video_title}")]')
  169. if video_title_element is None:
  170. Common.logger(self.log_type, self.crawler).warning(
  171. f"未找到该视频标题的element:{video_title_element}")
  172. return
  173. Common.logger(self.log_type, self.crawler).info("点击标题,进入视频详情页")
  174. self.get_video_url(video_title_element)
  175. video_mid_elements = self.search_elements("//wx-view[@class='bar--navBar-content-capsule-wrap']")
  176. mid = int(video_mid_elements[0].get_attribute("data-mid"))
  177. repeat_video_id = self.repeat_video_id(mid)
  178. if repeat_video_id:
  179. Common.logger(self.log_type, self.crawler).info(f"该用户已经存在")
  180. # status = 0
  181. # self.insert_user(mid, user_name, data_list, status)
  182. self.driver.press_keycode(AndroidKey.BACK)
  183. return
  184. data_list = self.get_user_list(mid)
  185. if len(data_list) == 0:
  186. Common.logger(self.log_type, self.crawler).info(f"不满足抓取条件")
  187. self.driver.press_keycode(AndroidKey.BACK)
  188. return
  189. else:
  190. status = 1
  191. localtime = time.localtime(time.time())
  192. formatted_time = time.strftime("%Y-%m-%d", localtime)
  193. print(formatted_time)
  194. self.insert_user(mid, user_name, data_list, status, formatted_time)
  195. values = [[
  196. mid, user_name, formatted_time, data_list
  197. ]]
  198. Feishu.insert_columns('xiaoniangao', 'xiaoniangao', "8zlceR", "ROWS", 1, 2)
  199. time.sleep(0.5)
  200. Feishu.update_values('xiaoniangao', 'xiaoniangao', "8zlceR", "A2:Z2", values)
  201. Common.logger(self.log_type, self.crawler).info(f"{mid}:{user_name}写入成功")
  202. AliyunLogger.logging(
  203. code="1010",
  204. platform=self.platform,
  205. mode=self.log_type,
  206. env=self.env,
  207. message=f"{mid}:{user_name}入库",
  208. )
  209. self.driver.press_keycode(AndroidKey.BACK)
  210. time.sleep(2)
  211. def insert_user(self, mid, user_name, data_list, status, formatted_time):
  212. insert_sql = f"""insert into crawler_xng_userid( user_id , user_name , user_title_text , status, time) values ({mid},"{user_name}", "{data_list}",{status}, "{formatted_time}")"""
  213. print(insert_sql)
  214. MysqlHelper.update_values(self.log_type, self.crawler, insert_sql, self.env, action='')
  215. def get_user_list(self, mid):
  216. next_t = -1
  217. url = "https://kapi-xng-app.xiaoniangao.cn/v1/album/user_public"
  218. headers = {
  219. 'Host': 'kapi-xng-app.xiaoniangao.cn',
  220. 'content-type': 'application/json; charset=utf-8',
  221. 'accept': '*/*',
  222. 'authorization': 'hSNQ2s9pvPxvFn4LaQJxKQ6/7Is=',
  223. 'verb': 'POST',
  224. 'content-md5': 'c7b7f8663984e8800e3bcd9b44465083',
  225. 'x-b3-traceid': '2f9da41f960ae077',
  226. 'accept-language': 'zh-cn',
  227. 'date': 'Mon, 19 Jun 2023 06:41:17 GMT',
  228. 'x-token-id': '',
  229. 'x-signaturemethod': 'hmac-sha1',
  230. 'user-agent': 'xngapp/157 CFNetwork/1335.0.3.1 Darwin/21.6.0'
  231. }
  232. payload = {
  233. "token": "",
  234. "limit": 20,
  235. "start_t": next_t,
  236. "visited_mid": mid,
  237. "share_width": 300,
  238. "share_height": 240,
  239. }
  240. response = requests.request(
  241. "POST",
  242. url,
  243. headers=headers,
  244. data=json.dumps(payload),
  245. )
  246. data_list = []
  247. if "data" not in response.text or response.status_code != 200:
  248. return data_list
  249. elif "list" not in response.json()["data"]:
  250. return data_list
  251. elif len(response.json()["data"]["list"]) == 0:
  252. return data_list
  253. list = response.json()["data"]["list"]
  254. for video_obj in list:
  255. video_title = clean_title(video_obj.get("title", ""))
  256. # 发布时间
  257. publish_time_stamp = int(int(video_obj.get("t", 0)) / 1000)
  258. publish_time_str = time.strftime(
  259. "%Y-%m-%d", time.localtime(publish_time_stamp)
  260. )
  261. date_three_days_ago_string = (date.today() + timedelta(days=-7)).strftime("%Y-%m-%d")
  262. rule = publish_time_str >= date_three_days_ago_string
  263. if rule == False:
  264. return ""
  265. v_url = video_obj.get("v_url")
  266. data_list.append(video_title + ":" + v_url)
  267. return data_list
  268. def repeat_video_id(self,mid):
  269. sql = f"SELECT `link` FROM `crawler_user_v3` WHERE `source` = 'xiaoniangao' and `link` = {mid}"
  270. repeat_video_id = MysqlHelper.get_values(self.log_type, self.crawler, sql, self.env)
  271. return len(repeat_video_id)
  272. def get_video_info(self, video_element):
  273. try:
  274. self.get_video_info_2(video_element)
  275. except Exception as e:
  276. self.driver.press_keycode(AndroidKey.BACK)
  277. Common.logger(self.log_type, self.crawler).error(f"抓取单条视频异常:{e}\n")
  278. def get_videoList(self):
  279. self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
  280. self.driver.implicitly_wait(20)
  281. # 切换到 web_view
  282. self.check_to_applet(xpath='//*[@class="tab-bar--tab tab-bar--tab-selected"]')
  283. print("切换到 webview 成功")
  284. time.sleep(1)
  285. if self.search_elements('//*[@class="list-list--list"]') is None:
  286. Common.logger(self.log_type, self.crawler).info("窗口已销毁\n")
  287. self.count = 0
  288. self.download_cnt = 0
  289. self.element_list = []
  290. return
  291. print("开始获取视频信息")
  292. for i in range(50):
  293. print("下滑{}次".format(i))
  294. element = self.parse_detail(i)
  295. self.get_video_info(element)
  296. self.swipe_up()
  297. time.sleep(1)
  298. if self.swipe_count > 100:
  299. return
  300. print("下滑完成")
  301. Common.logger(self.log_type, self.crawler).info("已抓取完一组,休眠 5 秒\n")
  302. time.sleep(5)
  303. def run():
  304. rule_dict1 = {"period": {"min": 365, "max": 365},
  305. "duration": {"min": 30, "max": 1800},
  306. "favorite_cnt": {"min": 0, "max": 0},
  307. "videos_cnt": {"min": 5000, "max": 0},
  308. "share_cnt": {"min": 0, "max": 0}}
  309. XiaoNianGaoPlusRecommend("recommend", "xiaoniangao", "prod", rule_dict1, 6267141)
  310. if __name__ == "__main__":
  311. process = multiprocessing.Process(
  312. target=run
  313. )
  314. process.start()
  315. while True:
  316. if not process.is_alive():
  317. print("正在重启")
  318. process.terminate()
  319. time.sleep(60)
  320. os.system("adb forward --remove-all")
  321. process = multiprocessing.Process(target=run)
  322. process.start()
  323. time.sleep(60)