shipinhao_search.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/25
  4. import datetime
  5. import json
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. from datetime import date, timedelta
  11. from hashlib import md5
  12. from appium import webdriver
  13. from appium.webdriver.extensions.android.nativekey import AndroidKey
  14. from appium.webdriver.webdriver import WebDriver
  15. from selenium.common import NoSuchElementException
  16. from selenium.webdriver.common.by import By
  17. sys.path.append(os.getcwd())
  18. from common.feishu import Feishu
  19. from common.publish import Publish
  20. from common.common import Common
  21. from common.getuser import getUser
  22. from common.scheduling_db import MysqlHelper
  23. class ShipinhaoSearch:
  24. platform = "视频号"
  25. i = 0
  26. download_cnt = 0
  27. @staticmethod
  28. def rule_dict(log_type, crawler):
  29. while True:
  30. shipinhao_rule_sheet = Feishu.get_values_batch(log_type, crawler, "YhfkNY")
  31. if shipinhao_rule_sheet is None:
  32. Common.logger(log_type, crawler).warning(f"shipinhao_rule_sheet:{shipinhao_rule_sheet}\n")
  33. time.sleep(3)
  34. continue
  35. rule_duration_min = int(shipinhao_rule_sheet[1][0])
  36. rule_duration_max = int(shipinhao_rule_sheet[1][2])
  37. rule_share_cnt_min = int(shipinhao_rule_sheet[2][0])
  38. rule_share_cnt_max = int(shipinhao_rule_sheet[2][2])
  39. rule_favorite_cnt_min = int(shipinhao_rule_sheet[3][0])
  40. rule_favorite_cnt_max = int(shipinhao_rule_sheet[3][2])
  41. rule_publish_time_min = shipinhao_rule_sheet[4][0]
  42. rule_publish_time_min_str = f"{str(rule_publish_time_min)[:4]}-{str(rule_publish_time_min)[4:6]}-{str(rule_publish_time_min)[6:]}"
  43. rule_publish_time_min = int(time.mktime(time.strptime(rule_publish_time_min_str, "%Y-%m-%d")))
  44. rule_publish_time_max = shipinhao_rule_sheet[4][2]
  45. rule_publish_time_max_str = f"{str(rule_publish_time_max)[:4]}-{str(rule_publish_time_max)[4:6]}-{str(rule_publish_time_max)[6:]}"
  46. rule_publish_time_max = int(time.mktime(time.strptime(rule_publish_time_max_str, "%Y-%m-%d")))
  47. videos_cnt = Feishu.get_values_batch(log_type, crawler, "YhfkNY")[5][2]
  48. rule_like_cnt_min = int(shipinhao_rule_sheet[6][0])
  49. rule_like_cnt_max = int(shipinhao_rule_sheet[6][2])
  50. rule_comment_cnt_min = int(shipinhao_rule_sheet[7][0])
  51. rule_comment_cnt_max = int(shipinhao_rule_sheet[7][2])
  52. rule_width_min = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[8][0])
  53. rule_width_max = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[8][2])
  54. rule_height_min = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[9][0])
  55. rule_height_max = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[9][2])
  56. rule_dict = {
  57. "duration": {"min": rule_duration_min, "max": rule_duration_max},
  58. "share_cnt": {"min": rule_share_cnt_min, "max": rule_share_cnt_max},
  59. "favorite_cnt": {"min": rule_favorite_cnt_min, "max": rule_favorite_cnt_max},
  60. "publish_time": {"min": rule_publish_time_min, "max": rule_publish_time_max},
  61. "videos_cnt": {"min": videos_cnt},
  62. "like_cnt": {"min": rule_like_cnt_min, "max": rule_like_cnt_max},
  63. "comment_cnt": {"min": rule_comment_cnt_min, "max": rule_comment_cnt_max},
  64. "width": {"min": rule_width_min, "max": rule_width_max},
  65. "height": {"min": rule_height_min, "max": rule_height_max},
  66. }
  67. return rule_dict
  68. # 基础门槛规则
  69. @staticmethod
  70. def download_rule(log_type, crawler, video_dict):
  71. """
  72. 下载视频的基本规则
  73. :param log_type: 日志
  74. :param crawler: 哪款爬虫
  75. :param video_dict: 视频信息,字典格式
  76. :return: 满足规则,返回 True;反之,返回 False
  77. """
  78. while True:
  79. shipinhao_rule_sheet = Feishu.get_values_batch(log_type, crawler, "YhfkNY")
  80. if shipinhao_rule_sheet is None:
  81. Common.logger(log_type, crawler).warning(f"shipinhao_rule_sheet:{shipinhao_rule_sheet}\n")
  82. time.sleep(3)
  83. continue
  84. rule_duration_min = int(shipinhao_rule_sheet[1][0])
  85. rule_duration_max = int(shipinhao_rule_sheet[1][2])
  86. rule_share_cnt_min = int(shipinhao_rule_sheet[2][0])
  87. rule_share_cnt_max = int(shipinhao_rule_sheet[2][2])
  88. rule_favorite_cnt_min = int(shipinhao_rule_sheet[3][0])
  89. rule_favorite_cnt_max = int(shipinhao_rule_sheet[3][2])
  90. rule_publish_time_min = shipinhao_rule_sheet[4][0]
  91. rule_publish_time_min_str = f"{str(rule_publish_time_min)[:4]}-{str(rule_publish_time_min)[4:6]}-{str(rule_publish_time_min)[6:]}"
  92. rule_publish_time_min = int(time.mktime(time.strptime(rule_publish_time_min_str, "%Y-%m-%d")))
  93. rule_publish_time_max = shipinhao_rule_sheet[4][2]
  94. rule_publish_time_max_str = f"{str(rule_publish_time_max)[:4]}-{str(rule_publish_time_max)[4:6]}-{str(rule_publish_time_max)[6:]}"
  95. rule_publish_time_max = int(time.mktime(time.strptime(rule_publish_time_max_str, "%Y-%m-%d")))
  96. # videos_cnt = Feishu.get_values_batch(log_type, crawler, "YhfkNY")[5][2]
  97. rule_like_cnt_min = int(shipinhao_rule_sheet[6][0])
  98. rule_like_cnt_max = int(shipinhao_rule_sheet[6][2])
  99. rule_comment_cnt_min = int(shipinhao_rule_sheet[7][0])
  100. rule_comment_cnt_max = int(shipinhao_rule_sheet[7][2])
  101. Common.logger(log_type, crawler).info(
  102. f'rule_duration_max:{rule_duration_max} >= duration:{int(float(video_dict["duration"]))} >= rule_duration_min:{int(rule_duration_min)}')
  103. Common.logger(log_type, crawler).info(
  104. f'rule_like_cnt_max:{int(rule_like_cnt_max)} >= like_cnt:{int(video_dict["like_cnt"])} >= rule_like_cnt_min:{int(rule_like_cnt_min)}')
  105. Common.logger(log_type, crawler).info(
  106. f'rule_comment_cnt_max:{int(rule_comment_cnt_max)} >= comment_cnt:{int(video_dict["comment_cnt"])} >= rule_comment_cnt_min:{int(rule_comment_cnt_min)}')
  107. Common.logger(log_type, crawler).info(
  108. f'rule_share_cnt_max:{int(rule_share_cnt_max)} >= share_cnt:{int(video_dict["share_cnt"])} >= rule_share_cnt_min:{int(rule_share_cnt_min)}')
  109. Common.logger(log_type, crawler).info(
  110. f'rule_favorite_cnt_max:{int(rule_favorite_cnt_max)} >= favorite_cnt:{int(video_dict["favorite_cnt"])} >= rule_favorite_cnt_min:{int(rule_favorite_cnt_min)}')
  111. Common.logger(log_type, crawler).info(
  112. f'rule_publish_time_max:{int(rule_publish_time_max)} >= publish_time_stamp:{int(video_dict["publish_time_stamp"])} >= rule_publish_time_min:{int(rule_publish_time_min)}')
  113. if int(rule_duration_max) >= int(float(video_dict["duration"])) >= int(rule_duration_min) \
  114. and int(rule_like_cnt_max) >= int(video_dict['like_cnt']) >= int(rule_like_cnt_min) \
  115. and int(rule_comment_cnt_max) >= int(video_dict['comment_cnt']) >= int(rule_comment_cnt_min) \
  116. and int(rule_share_cnt_max) >= int(video_dict['share_cnt']) >= int(rule_share_cnt_min) \
  117. and int(rule_favorite_cnt_max) >= int(video_dict['favorite_cnt']) >= int(rule_favorite_cnt_min) \
  118. and int(rule_publish_time_max) >= int(video_dict['publish_time_stamp']) >= int(rule_publish_time_min):
  119. return True
  120. else:
  121. return False
  122. @staticmethod
  123. def width_height_rule(log_type, crawler, width, height):
  124. while True:
  125. shipinhao_rule_sheet = Feishu.get_values_batch(log_type, crawler, "YhfkNY")
  126. if shipinhao_rule_sheet is None:
  127. Common.logger(log_type, crawler).warning(f"shipinhao_rule_sheet:{shipinhao_rule_sheet}\n")
  128. time.sleep(3)
  129. continue
  130. rule_width_min = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[8][0])
  131. rule_width_max = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[8][2])
  132. rule_height_min = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[9][0])
  133. rule_height_max = int(Feishu.get_values_batch(log_type, crawler, "YhfkNY")[9][2])
  134. Common.logger(log_type, crawler).info(
  135. f'rule_width_max:{int(rule_width_max)} >= width:{int(width)} >= rule_width_min:{int(rule_width_min)}')
  136. Common.logger(log_type, crawler).info(
  137. f'rule_height_max:{int(rule_height_max)} >= width:{int(height)} >= rule_height_min:{int(rule_height_min)}')
  138. if rule_width_max >= int(width) >= rule_width_min and rule_height_max >= int(height) >= rule_height_min:
  139. return True
  140. else:
  141. return False
  142. @staticmethod
  143. def videos_cnt(log_type, crawler):
  144. while True:
  145. shipinhao_rule_sheet = Feishu.get_values_batch(log_type, crawler, "YhfkNY")
  146. if shipinhao_rule_sheet is None:
  147. Common.logger(log_type, crawler).warning(f"shipinhao_rule_sheet:{shipinhao_rule_sheet}\n")
  148. time.sleep(3)
  149. continue
  150. videos_cnt = Feishu.get_values_batch(log_type, crawler, "YhfkNY")[5][2]
  151. return int(videos_cnt)
  152. @classmethod
  153. def start_wechat(cls, log_type, crawler, word, our_uid, env):
  154. Common.logger(log_type, crawler).info('启动微信')
  155. if env == "dev":
  156. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver"
  157. else:
  158. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  159. caps = {
  160. "platformName": "Android", # 手机操作系统 Android / iOS
  161. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  162. "platforVersion": "13", # 手机对应的系统版本(Android 13)
  163. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  164. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  165. "autoGrantPermissions": True, # 让 appium 自动授权 base 权限,
  166. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  167. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  168. "resetkeyboard": True, # 执行完程序恢复原来输入法
  169. "noReset": True, # 不重置APP
  170. "recreateChromeDriverSessions": True, # 切换到非 chrome-Driver 会 kill 掉 session,就不需要手动 kill 了
  171. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  172. "newCommandTimeout": 6000, # 初始等待时间
  173. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  174. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  175. "showChromedriverLog": True,
  176. # "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  177. "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  178. # "chromeOptions": {"androidProcess": "com.tencent.mm"},
  179. 'enableWebviewDetailsCollection': True,
  180. 'setWebContentsDebuggingEnabled': True,
  181. 'chromedriverExecutable': chromedriverExecutable,
  182. }
  183. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  184. driver.implicitly_wait(10)
  185. Common.logger(log_type, crawler).info("点击微信")
  186. # if len(driver.find_elements(By.ID, 'android:id/text1')) != 0:
  187. # driver.find_elements(By.ID, 'android:id/text1')[0].click()
  188. Common.logger(log_type, crawler).info("等待 5s")
  189. time.sleep(5)
  190. cls.search_video(log_type=log_type,
  191. crawler=crawler,
  192. word=word,
  193. our_uid=our_uid,
  194. driver=driver,
  195. env=env)
  196. cls.close_wechat(log_type=log_type,
  197. crawler=crawler,
  198. driver=driver)
  199. @classmethod
  200. def close_wechat(cls, log_type, crawler, driver: WebDriver):
  201. driver.quit()
  202. Common.logger(log_type, crawler).info(f"微信退出成功\n")
  203. @classmethod
  204. def is_contain_chinese(cls, strword):
  205. for ch in strword:
  206. if u'\u4e00' <= ch <= u'\u9fff':
  207. return True
  208. return False
  209. # 查找元素
  210. @classmethod
  211. def search_elements(cls, driver: WebDriver, xpath):
  212. time.sleep(1)
  213. windowHandles = driver.window_handles
  214. for handle in windowHandles:
  215. driver.switch_to.window(handle)
  216. time.sleep(1)
  217. try:
  218. elements = driver.find_elements(By.XPATH, xpath)
  219. if elements:
  220. return elements
  221. except NoSuchElementException:
  222. pass
  223. @classmethod
  224. def check_to_webview(cls, log_type, crawler, driver: WebDriver):
  225. # Common.logger(log_type, crawler).info('切换到webview')
  226. webviews = driver.contexts
  227. Common.logger(log_type, crawler).info(f"webviews:{webviews}")
  228. driver.switch_to.context(webviews[1])
  229. time.sleep(1)
  230. windowHandles = driver.window_handles
  231. for handle in windowHandles:
  232. driver.switch_to.window(handle)
  233. try:
  234. shipinhao_webview = driver.find_element(By.XPATH, '//div[@class="unit"]')
  235. if shipinhao_webview:
  236. Common.logger(log_type, crawler).info('切换到视频号 webview 成功')
  237. return "成功"
  238. except Exception as e:
  239. Common.logger(log_type, crawler).info(f"{e}\n")
  240. @classmethod
  241. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  242. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{out_video_id}"; """
  243. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  244. return len(repeat_video)
  245. @classmethod
  246. def repeat_video_url(cls, log_type, crawler, video_url, env):
  247. sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
  248. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  249. return len(repeat_video)
  250. @classmethod
  251. def search_video(cls, log_type, crawler, word, driver: WebDriver, our_uid, env):
  252. # 点击微信搜索框,并输入搜索词
  253. driver.implicitly_wait(10)
  254. Common.logger(log_type, crawler).info("点击微信搜索框")
  255. driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()
  256. time.sleep(0.5)
  257. Common.logger(log_type, crawler).info(f'输入搜索词:{word}')
  258. driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)
  259. driver.press_keycode(AndroidKey.ENTER)
  260. # driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  261. Common.logger(log_type, crawler).info("点击搜索,进入搜索页")
  262. # driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  263. driver.find_elements(By.ID, 'com.tencent.mm:id/br8')[0].click()
  264. time.sleep(5)
  265. # 切换到微信搜索结果页 webview
  266. check_to_webview = cls.check_to_webview(log_type, crawler, driver)
  267. if check_to_webview is None:
  268. Common.logger(log_type, crawler).info("切换到视频号 webview 失败\n")
  269. return
  270. time.sleep(1)
  271. # 切换到"视频号"分类
  272. shipinhao_tags = cls.search_elements(driver, '//div[@class="unit"]/*[2]')
  273. Common.logger(log_type, crawler).info('点击"视频号"分类')
  274. shipinhao_tags[0].click()
  275. time.sleep(5)
  276. index = 0
  277. while True:
  278. # try:
  279. if cls.search_elements(driver, '//*[@class="double-rich double-rich_vertical"]') is None:
  280. Common.logger(log_type, crawler).info('窗口已销毁\n')
  281. return
  282. Common.logger(log_type, crawler).info('获取视频列表\n')
  283. video_elements = cls.search_elements(driver, '//div[@class="vc active__mask"]')
  284. if video_elements is None:
  285. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  286. return
  287. video_element_temp = video_elements[index:]
  288. if len(video_element_temp) == 0:
  289. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  290. return
  291. for i, video_element in enumerate(video_element_temp):
  292. Common.logger(log_type, crawler).info(f"download_cnt:{cls.download_cnt}")
  293. if cls.download_cnt >= cls.videos_cnt(log_type, crawler):
  294. Common.logger(log_type, crawler).info(f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
  295. cls.download_cnt = 0
  296. return
  297. if video_element is None:
  298. Common.logger(log_type, crawler).info('到底啦~\n')
  299. return
  300. cls.i += 1
  301. cls.search_elements(driver, '//div[@class="vc active__mask"]')
  302. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  303. time.sleep(3)
  304. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
  305. video_element)
  306. if len(video_element.find_elements(By.XPATH, "//*[@text='没有更多的搜索结果']")) != 0:
  307. Common.logger(log_type, crawler).info("没有更多的搜索结果\n")
  308. return
  309. video_title = video_element.find_elements(By.XPATH, '//div[@class="title ellipsis_2"]/*[2]')[index + i].text[:40]
  310. video_url = video_element.find_elements(By.XPATH, '//div[@class="video-player"]')[index+i].get_attribute('src')
  311. cover_url = video_element.find_elements(By.XPATH, '//div[@class="video-player__bd"]')[index+i].get_attribute('style')
  312. cover_url = cover_url.split('url("')[-1].split('")')[0]
  313. duration = video_element.find_elements(By.XPATH, '//div[@class="play-mask__text"]/*[2]')[index+i].text
  314. duration = int(duration.split(':')[0]) * 60 + int(duration.split(':')[-1])
  315. user_name = video_element.find_elements(By.XPATH, '//p[@class="vc-source__text"]')[index+i].text
  316. avatar_url = video_element.find_elements(By.XPATH, '//div[@class="ui-image-image ui-image vc-source__thumb"]')[index+i].get_attribute('style')
  317. avatar_url = avatar_url.split('url("')[-1].split('")')[0]
  318. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  319. out_user_id = md5(user_name.encode('utf8')).hexdigest()
  320. video_dict = {
  321. "video_title": video_title,
  322. "video_id": out_video_id,
  323. "play_cnt": 0,
  324. "duration": duration,
  325. "user_name": user_name,
  326. "user_id": out_user_id,
  327. "avatar_url": avatar_url,
  328. "cover_url": cover_url,
  329. "video_url": video_url,
  330. "session": f"shipinhao-search-{int(time.time())}"
  331. }
  332. for k, v in video_dict.items():
  333. Common.logger(log_type, crawler).info(f"{k}:{v}")
  334. if video_title is None or video_url is None:
  335. Common.logger(log_type, crawler).info("无效视频\n")
  336. elif cls.repeat_out_video_id(log_type, crawler, out_video_id, env) != 0:
  337. Common.logger(log_type, crawler).info('视频已下载\n')
  338. elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
  339. Common.logger(log_type, crawler).info('视频已下载\n')
  340. else:
  341. video_element.click()
  342. time.sleep(3)
  343. video_info_dict = cls.get_video_info(driver)
  344. video_dict["like_cnt"] = video_info_dict["like_cnt"]
  345. video_dict["share_cnt"] = video_info_dict["share_cnt"]
  346. video_dict["favorite_cnt"] = video_info_dict["favorite_cnt"]
  347. video_dict["comment_cnt"] = video_info_dict["comment_cnt"]
  348. video_dict["publish_time_str"] = video_info_dict["publish_time_str"]
  349. video_dict["publish_time_stamp"] = video_info_dict["publish_time_stamp"]
  350. Common.logger(log_type, crawler).info(f'publish_time:{video_dict["publish_time_str"]}')
  351. if cls.download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict) is False:
  352. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  353. else:
  354. cls.download_publish(log_type=log_type,
  355. crawler=crawler,
  356. word=word,
  357. video_dict=video_dict,
  358. our_uid=our_uid,
  359. env=env)
  360. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠1秒\n')
  361. time.sleep(1)
  362. index = index + len(video_element_temp)
  363. # except Exception as e:
  364. # Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  365. # cls.i = 0
  366. @classmethod
  367. def download_publish(cls, log_type, crawler, word, video_dict, our_uid, env):
  368. # 下载视频
  369. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  370. # ffmpeg 获取视频宽高
  371. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  372. if ffmpeg_dict is None:
  373. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  374. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  375. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  376. return
  377. video_dict["video_width"] = ffmpeg_dict["width"]
  378. video_dict["video_height"] = ffmpeg_dict["height"]
  379. # 规则判断
  380. if cls.width_height_rule(log_type, crawler, video_dict["video_width"], video_dict["video_height"]) is False:
  381. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  382. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  383. Common.logger(log_type, crawler).info("宽高不满足抓取规则,删除成功\n")
  384. return
  385. # 下载封面
  386. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  387. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  388. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  389. # 上传视频
  390. Common.logger(log_type, crawler).info("开始上传视频...")
  391. our_video_id = Publish.upload_and_publish(log_type=log_type,
  392. crawler=crawler,
  393. strategy="搜索爬虫策略",
  394. our_uid=our_uid,
  395. env=env,
  396. oss_endpoint="out")
  397. if env == "dev":
  398. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  399. else:
  400. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  401. Common.logger(log_type, crawler).info("视频上传完成")
  402. if our_video_id is None:
  403. try:
  404. # 删除视频文件夹
  405. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  406. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  407. Common.logger(log_type, crawler).warning(f"our_video_id:{our_video_id}, 删除成功\n")
  408. return
  409. except FileNotFoundError:
  410. return
  411. rule_dict = cls.rule_dict(log_type, crawler)
  412. insert_sql = f""" insert into crawler_video(video_id,
  413. out_user_id,
  414. platform,
  415. strategy,
  416. out_video_id,
  417. video_title,
  418. cover_url,
  419. video_url,
  420. duration,
  421. publish_time,
  422. play_cnt,
  423. crawler_rule,
  424. width,
  425. height)
  426. values({our_video_id},
  427. "{video_dict['user_id']}",
  428. "{cls.platform}",
  429. "搜索爬虫策略",
  430. "{video_dict['video_id']}",
  431. "{video_dict['video_title']}",
  432. "{video_dict['cover_url']}",
  433. "{video_dict['video_url']}",
  434. {int(video_dict['duration'])},
  435. "{video_dict['publish_time_str']}",
  436. {int(video_dict['play_cnt'])},
  437. '{json.dumps(rule_dict)}',
  438. {int(video_dict['video_width'])},
  439. {int(video_dict['video_height'])}) """
  440. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  441. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  442. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  443. # 写飞书
  444. Feishu.insert_columns(log_type, crawler, "xYWCzf", "ROWS", 1, 2)
  445. time.sleep(0.5)
  446. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  447. "搜索爬虫策略",
  448. word,
  449. video_dict["video_title"],
  450. our_video_link,
  451. video_dict["duration"],
  452. video_dict["like_cnt"],
  453. video_dict["share_cnt"],
  454. video_dict["favorite_cnt"],
  455. video_dict["comment_cnt"],
  456. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  457. video_dict["publish_time_str"],
  458. video_dict["user_name"],
  459. video_dict["avatar_url"],
  460. video_dict["cover_url"],
  461. video_dict["video_url"]]]
  462. Feishu.update_values(log_type, crawler, "xYWCzf", "F2:Z2", values)
  463. Common.logger(log_type, crawler).info("写入飞书成功\n")
  464. cls.download_cnt += 1
  465. @classmethod
  466. def get_video_info(cls, driver: WebDriver):
  467. # Common.logger(log_type, crawler).info('切回NATIVE_APP')
  468. driver.switch_to.context('NATIVE_APP')
  469. # 点赞
  470. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  471. like_cnt = like_id.get_attribute('name')
  472. if like_cnt == "" or like_cnt == "喜欢" or like_cnt == "火" or cls.is_contain_chinese(like_cnt) is True:
  473. like_cnt = 0
  474. elif '万' in like_cnt:
  475. like_cnt = int(float(like_cnt.split('万')[0]) * 10000)
  476. elif '万+' in like_cnt:
  477. like_cnt = int(float(like_cnt.split('万+')[0]) * 10000)
  478. else:
  479. like_cnt = int(float(like_cnt))
  480. # 分享
  481. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  482. share_cnt = share_id.get_attribute('name')
  483. if share_cnt == "" or share_cnt == "转发" or cls.is_contain_chinese(share_cnt) is True:
  484. share_cnt = 0
  485. elif '万' in share_cnt:
  486. share_cnt = int(float(share_cnt.split('万')[0]) * 10000)
  487. elif '万+' in share_cnt:
  488. share_cnt = int(float(share_cnt.split('万+')[0]) * 10000)
  489. else:
  490. share_cnt = int(float(share_cnt))
  491. # 收藏
  492. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  493. favorite_cnt = favorite_id.get_attribute('name')
  494. if favorite_cnt == "" or favorite_cnt == "收藏" or favorite_cnt == "推荐" or favorite_cnt == "火" or cls.is_contain_chinese(favorite_cnt) is True:
  495. favorite_cnt = 0
  496. elif '万' in favorite_cnt:
  497. favorite_cnt = int(float(favorite_cnt.split('万')[0]) * 10000)
  498. elif '万+' in favorite_cnt:
  499. favorite_cnt = int(float(favorite_cnt.split('万+')[0]) * 10000)
  500. else:
  501. favorite_cnt = int(float(favorite_cnt))
  502. # 评论
  503. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  504. comment_cnt = comment_id.get_attribute('name')
  505. if comment_cnt == "" or comment_cnt == "评论" or cls.is_contain_chinese(comment_cnt) is True:
  506. comment_cnt = 0
  507. elif '万' in comment_cnt:
  508. comment_cnt = int(float(comment_cnt.split('万')[0]) * 10000)
  509. elif '万+' in comment_cnt:
  510. comment_cnt = int(float(comment_cnt.split('万+')[0]) * 10000)
  511. else:
  512. comment_cnt = int(float(comment_cnt))
  513. # 发布时间
  514. comment_id.click()
  515. time.sleep(1)
  516. publish_time = driver.find_element(By.ID, "com.tencent.mm:id/bre").get_attribute("name")
  517. if "秒" in publish_time or "分钟" in publish_time or "小时" in publish_time:
  518. publish_time_str = (date.today() + timedelta(days=0)).strftime("%Y-%m-%d")
  519. elif "天前" in publish_time:
  520. days = int(publish_time.replace("天前", ""))
  521. publish_time_str = (date.today() + timedelta(days=-days)).strftime("%Y-%m-%d")
  522. elif "年" in publish_time:
  523. # publish_time_str = publish_time.replace("年", "-").replace("月", "-").replace("日", "")
  524. year_str = publish_time.split("年")[0]
  525. month_str = publish_time.split("年")[-1].split("月")[0]
  526. day_str = publish_time.split("月")[-1].split("日")[0]
  527. if int(month_str) < 10:
  528. month_str = f"0{month_str}"
  529. if int(day_str) < 10:
  530. day_str = f"0{day_str}"
  531. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  532. else:
  533. year_str = str(datetime.datetime.now().year)
  534. month_str = publish_time.split("月")[0]
  535. day_str = publish_time.split("月")[-1].split("日")[0]
  536. if int(month_str) < 10:
  537. month_str = f"0{month_str}"
  538. if int(day_str) < 10:
  539. day_str = f"0{day_str}"
  540. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  541. # publish_time_str = f'2023-{publish_time.replace("月", "-").replace("日", "")}'
  542. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y-%m-%d")))
  543. # 收起评论
  544. # Common.logger(log_type, crawler).info("收起评论")
  545. driver.find_element(By.ID, "com.tencent.mm:id/be_").click()
  546. time.sleep(0.5)
  547. # 返回 webview
  548. # Common.logger(log_type, crawler).info(f"操作手机返回按键")
  549. driver.find_element(By.ID, "com.tencent.mm:id/a2z").click()
  550. time.sleep(0.5)
  551. # driver.press_keycode(AndroidKey.BACK)
  552. # cls.check_to_webview(log_type=log_type, crawler=crawler, driver=driver)
  553. webviews = driver.contexts
  554. driver.switch_to.context(webviews[1])
  555. video_dict = {
  556. "like_cnt": like_cnt,
  557. "share_cnt": share_cnt,
  558. "favorite_cnt": favorite_cnt,
  559. "comment_cnt": comment_cnt,
  560. "publish_time_str": publish_time_str,
  561. "publish_time_stamp": publish_time_stamp,
  562. }
  563. return video_dict
  564. @classmethod
  565. def get_users(cls, log_type, crawler, sheetid, env):
  566. while True:
  567. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  568. if user_sheet is None:
  569. Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 3秒钟后重试")
  570. time.sleep(3)
  571. continue
  572. our_user_list = []
  573. for i in range(1, len(user_sheet)):
  574. # for i in range(1, 3):
  575. search_word = user_sheet[i][4]
  576. our_uid = user_sheet[i][6]
  577. tag1 = user_sheet[i][8]
  578. tag2 = user_sheet[i][9]
  579. tag3 = user_sheet[i][10]
  580. tag4 = user_sheet[i][11]
  581. tag5 = user_sheet[i][12]
  582. Common.logger(log_type, crawler).info(f"正在更新 {search_word} 搜索词信息")
  583. if our_uid is None:
  584. default_user = getUser.get_default_user()
  585. # 用来创建our_id的信息
  586. user_dict = {
  587. 'recommendStatus': -6,
  588. 'appRecommendStatus': -6,
  589. 'nickName': default_user['nickName'],
  590. 'avatarUrl': default_user['avatarUrl'],
  591. 'tagName': f'{tag1},{tag2},{tag3},{tag4},{tag5}',
  592. }
  593. our_uid = getUser.create_uid(log_type, crawler, user_dict, env)
  594. if env == 'prod':
  595. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  596. else:
  597. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  598. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}',
  599. [[our_uid, our_user_link]])
  600. Common.logger(log_type, crawler).info(f'站内用户主页创建成功:{our_user_link}\n')
  601. our_user_dict = {
  602. 'out_uid': '',
  603. 'search_word': search_word,
  604. 'our_uid': our_uid,
  605. 'our_user_link': f'https://admin.piaoquantv.com/ums/user/{our_uid}/post',
  606. }
  607. our_user_list.append(our_user_dict)
  608. return our_user_list
  609. @classmethod
  610. def get_search_videos(cls, log_type, crawler, env):
  611. user_list = cls.get_users(log_type, crawler, "wNgi6Z", env)
  612. for user in user_list:
  613. cls.i = 0
  614. cls.download_cnt = 0
  615. search_word = user["search_word"]
  616. our_uid = user["our_uid"]
  617. Common.logger(log_type, crawler).info(f"开始抓取搜索词:{search_word}")
  618. try:
  619. cls.start_wechat(log_type=log_type,
  620. crawler=crawler,
  621. word=search_word,
  622. our_uid=our_uid,
  623. env=env)
  624. except Exception as e:
  625. Common.logger(log_type, crawler).error(f"search_video:{e}\n")
  626. if __name__ == '__main__':
  627. # ShipinhaoSearchScheduling.get_search_videos(log_type="search",
  628. # crawler="shipinhao",
  629. # rule_dict='[{"videos_cnt":{"min":10,"max":0}},{"duration":{"min":30,"max":600}},{"share_cnt":{"min":3000,"max":0}},{"favorite_cnt":{"min":1000,"max":0}},{"publish_time":{"min":1672502400000,"max":0}}]',
  630. # oss_endpoint="out",
  631. # env="dev")
  632. # print(ShipinhaoSearchScheduling.get_users("search", "shipinhao", "wNgi6Z", "dev"))
  633. # print((date.today() + timedelta(days=0)).strftime("%Y-%m-%d"))
  634. # print(ShipinhaoSearchScheduling.repeat_out_video_id(log_type="search",
  635. # crawler="shipinhao",
  636. # out_video_id="123",
  637. # env="dev"))
  638. # ShipinhaoSearch.download_rule(log_type="search", crawler="shipinhao", video_dict={})
  639. print(ShipinhaoSearch.rule_dict(log_type="search", crawler="shipinhao"))
  640. pass