xiaoniangao_plus_get_userid.py 14 KB

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