shipinhao_search.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. if len(driver.find_elements(By.ID, 'android:id/text1')) != 0:
  186. driver.find_elements(By.ID, 'android:id/text1')[0].click()
  187. time.sleep(5)
  188. cls.search_video(log_type=log_type,
  189. crawler=crawler,
  190. word=word,
  191. our_uid=our_uid,
  192. driver=driver,
  193. env=env)
  194. cls.close_wechat(log_type=log_type,
  195. crawler=crawler,
  196. driver=driver)
  197. @classmethod
  198. def close_wechat(cls, log_type, crawler, driver: WebDriver):
  199. driver.quit()
  200. Common.logger(log_type, crawler).info(f"微信退出成功\n")
  201. @classmethod
  202. def is_contain_chinese(cls, strword):
  203. for ch in strword:
  204. if u'\u4e00' <= ch <= u'\u9fff':
  205. return True
  206. return False
  207. # 查找元素
  208. @classmethod
  209. def search_elements(cls, driver: WebDriver, xpath):
  210. time.sleep(1)
  211. windowHandles = driver.window_handles
  212. for handle in windowHandles:
  213. driver.switch_to.window(handle)
  214. time.sleep(1)
  215. try:
  216. elements = driver.find_elements(By.XPATH, xpath)
  217. if elements:
  218. return elements
  219. except NoSuchElementException:
  220. pass
  221. @classmethod
  222. def check_to_webview(cls, log_type, crawler, driver: WebDriver):
  223. # Common.logger(log_type, crawler).info('切换到webview')
  224. webviews = driver.contexts
  225. Common.logger(log_type, crawler).info(f"webviews:{webviews}")
  226. driver.switch_to.context(webviews[1])
  227. time.sleep(1)
  228. windowHandles = driver.window_handles
  229. for handle in windowHandles:
  230. driver.switch_to.window(handle)
  231. try:
  232. shipinhao_webview = driver.find_element(By.XPATH, '//div[@class="unit"]')
  233. if shipinhao_webview:
  234. Common.logger(log_type, crawler).info('切换到视频号 webview 成功')
  235. return "成功"
  236. except Exception as e:
  237. Common.logger(log_type, crawler).info(f"{e}\n")
  238. @classmethod
  239. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  240. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{out_video_id}"; """
  241. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  242. return len(repeat_video)
  243. @classmethod
  244. def repeat_video_url(cls, log_type, crawler, video_url, env):
  245. sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
  246. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  247. return len(repeat_video)
  248. @classmethod
  249. def search_video(cls, log_type, crawler, word, driver: WebDriver, our_uid, env):
  250. # 点击微信搜索框,并输入搜索词
  251. driver.implicitly_wait(10)
  252. driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()
  253. time.sleep(0.5)
  254. Common.logger(log_type, crawler).info(f'输入搜索词:{word}')
  255. driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)
  256. driver.press_keycode(AndroidKey.ENTER)
  257. # driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  258. driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  259. time.sleep(5)
  260. # 切换到微信搜索结果页 webview
  261. check_to_webview = cls.check_to_webview(log_type, crawler, driver)
  262. if check_to_webview is None:
  263. Common.logger(log_type, crawler).info("切换到视频号 webview 失败\n")
  264. return
  265. time.sleep(1)
  266. # 切换到"视频号"分类
  267. shipinhao_tags = cls.search_elements(driver, '//div[@class="unit"]/*[2]')
  268. Common.logger(log_type, crawler).info('点击"视频号"分类')
  269. shipinhao_tags[0].click()
  270. time.sleep(5)
  271. index = 0
  272. while True:
  273. # try:
  274. if cls.search_elements(driver, '//*[@class="double-rich double-rich_vertical"]') is None:
  275. Common.logger(log_type, crawler).info('窗口已销毁\n')
  276. return
  277. Common.logger(log_type, crawler).info('获取视频列表\n')
  278. video_elements = cls.search_elements(driver, '//div[@class="vc active__mask"]')
  279. if video_elements is None:
  280. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  281. return
  282. video_element_temp = video_elements[index:]
  283. if len(video_element_temp) == 0:
  284. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  285. return
  286. for i, video_element in enumerate(video_element_temp):
  287. Common.logger(log_type, crawler).info(f"download_cnt:{cls.download_cnt}")
  288. if cls.download_cnt >= cls.videos_cnt(log_type, crawler):
  289. Common.logger(log_type, crawler).info(f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
  290. cls.download_cnt = 0
  291. return
  292. if video_element is None:
  293. Common.logger(log_type, crawler).info('到底啦~\n')
  294. return
  295. cls.i += 1
  296. cls.search_elements(driver, '//div[@class="vc active__mask"]')
  297. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  298. time.sleep(3)
  299. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
  300. video_element)
  301. if len(video_element.find_elements(By.XPATH, "//*[@text='没有更多的搜索结果']")) != 0:
  302. Common.logger(log_type, crawler).info("没有更多的搜索结果\n")
  303. return
  304. video_title = video_element.find_elements(By.XPATH, '//div[@class="title ellipsis_2"]/*[2]')[index + i].text[:40]
  305. video_url = video_element.find_elements(By.XPATH, '//div[@class="video-player"]')[index+i].get_attribute('src')
  306. cover_url = video_element.find_elements(By.XPATH, '//div[@class="video-player__bd"]')[index+i].get_attribute('style')
  307. cover_url = cover_url.split('url("')[-1].split('")')[0]
  308. duration = video_element.find_elements(By.XPATH, '//div[@class="play-mask__text"]/*[2]')[index+i].text
  309. duration = int(duration.split(':')[0]) * 60 + int(duration.split(':')[-1])
  310. user_name = video_element.find_elements(By.XPATH, '//p[@class="vc-source__text"]')[index+i].text
  311. avatar_url = video_element.find_elements(By.XPATH, '//div[@class="ui-image-image ui-image vc-source__thumb"]')[index+i].get_attribute('style')
  312. avatar_url = avatar_url.split('url("')[-1].split('")')[0]
  313. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  314. out_user_id = md5(user_name.encode('utf8')).hexdigest()
  315. video_dict = {
  316. "video_title": video_title,
  317. "video_id": out_video_id,
  318. "play_cnt": 0,
  319. "duration": duration,
  320. "user_name": user_name,
  321. "user_id": out_user_id,
  322. "avatar_url": avatar_url,
  323. "cover_url": cover_url,
  324. "video_url": video_url,
  325. "session": f"shipinhao-search-{int(time.time())}"
  326. }
  327. for k, v in video_dict.items():
  328. Common.logger(log_type, crawler).info(f"{k}:{v}")
  329. if video_title is None or video_url is None:
  330. Common.logger(log_type, crawler).info("无效视频\n")
  331. elif cls.repeat_out_video_id(log_type, crawler, out_video_id, env) != 0:
  332. Common.logger(log_type, crawler).info('视频已下载\n')
  333. elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
  334. Common.logger(log_type, crawler).info('视频已下载\n')
  335. else:
  336. video_element.click()
  337. time.sleep(3)
  338. video_info_dict = cls.get_video_info(driver)
  339. video_dict["like_cnt"] = video_info_dict["like_cnt"]
  340. video_dict["share_cnt"] = video_info_dict["share_cnt"]
  341. video_dict["favorite_cnt"] = video_info_dict["favorite_cnt"]
  342. video_dict["comment_cnt"] = video_info_dict["comment_cnt"]
  343. video_dict["publish_time_str"] = video_info_dict["publish_time_str"]
  344. video_dict["publish_time_stamp"] = video_info_dict["publish_time_stamp"]
  345. Common.logger(log_type, crawler).info(f'publish_time:{video_dict["publish_time_str"]}')
  346. if cls.download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict) is False:
  347. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  348. else:
  349. cls.download_publish(log_type=log_type,
  350. crawler=crawler,
  351. word=word,
  352. video_dict=video_dict,
  353. our_uid=our_uid,
  354. env=env)
  355. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠1秒\n')
  356. time.sleep(1)
  357. index = index + len(video_element_temp)
  358. # except Exception as e:
  359. # Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  360. # cls.i = 0
  361. @classmethod
  362. def download_publish(cls, log_type, crawler, word, video_dict, our_uid, env):
  363. # 下载视频
  364. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  365. # ffmpeg 获取视频宽高
  366. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  367. if ffmpeg_dict is None:
  368. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  369. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  370. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  371. return
  372. video_dict["video_width"] = ffmpeg_dict["width"]
  373. video_dict["video_height"] = ffmpeg_dict["height"]
  374. # 规则判断
  375. if cls.width_height_rule(log_type, crawler, video_dict["video_width"], video_dict["video_height"]) is False:
  376. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  377. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  378. Common.logger(log_type, crawler).info("宽高不满足抓取规则,删除成功\n")
  379. return
  380. # 下载封面
  381. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  382. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  383. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  384. # 上传视频
  385. Common.logger(log_type, crawler).info("开始上传视频...")
  386. our_video_id = Publish.upload_and_publish(log_type=log_type,
  387. crawler=crawler,
  388. strategy="搜索爬虫策略",
  389. our_uid=our_uid,
  390. env=env,
  391. oss_endpoint="out")
  392. if env == "dev":
  393. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  394. else:
  395. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  396. Common.logger(log_type, crawler).info("视频上传完成")
  397. if our_video_id is None:
  398. try:
  399. # 删除视频文件夹
  400. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  401. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  402. Common.logger(log_type, crawler).warning(f"our_video_id:{our_video_id}, 删除成功\n")
  403. return
  404. except FileNotFoundError:
  405. return
  406. rule_dict = cls.rule_dict(log_type, crawler)
  407. insert_sql = f""" insert into crawler_video(video_id,
  408. out_user_id,
  409. platform,
  410. strategy,
  411. out_video_id,
  412. video_title,
  413. cover_url,
  414. video_url,
  415. duration,
  416. publish_time,
  417. play_cnt,
  418. crawler_rule,
  419. width,
  420. height)
  421. values({our_video_id},
  422. "{video_dict['user_id']}",
  423. "{cls.platform}",
  424. "搜索爬虫策略",
  425. "{video_dict['video_id']}",
  426. "{video_dict['video_title']}",
  427. "{video_dict['cover_url']}",
  428. "{video_dict['video_url']}",
  429. {int(video_dict['duration'])},
  430. "{video_dict['publish_time_str']}",
  431. {int(video_dict['play_cnt'])},
  432. '{json.dumps(rule_dict)}',
  433. {int(video_dict['video_width'])},
  434. {int(video_dict['video_height'])}) """
  435. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  436. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  437. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  438. # 写飞书
  439. Feishu.insert_columns(log_type, crawler, "xYWCzf", "ROWS", 1, 2)
  440. time.sleep(0.5)
  441. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  442. "搜索爬虫策略",
  443. word,
  444. video_dict["video_title"],
  445. our_video_link,
  446. video_dict["duration"],
  447. video_dict["like_cnt"],
  448. video_dict["share_cnt"],
  449. video_dict["favorite_cnt"],
  450. video_dict["comment_cnt"],
  451. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  452. video_dict["publish_time_str"],
  453. video_dict["user_name"],
  454. video_dict["avatar_url"],
  455. video_dict["cover_url"],
  456. video_dict["video_url"]]]
  457. Feishu.update_values(log_type, crawler, "xYWCzf", "F2:Z2", values)
  458. Common.logger(log_type, crawler).info("写入飞书成功\n")
  459. cls.download_cnt += 1
  460. @classmethod
  461. def get_video_info(cls, driver: WebDriver):
  462. # Common.logger(log_type, crawler).info('切回NATIVE_APP')
  463. driver.switch_to.context('NATIVE_APP')
  464. # 点赞
  465. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  466. like_cnt = like_id.get_attribute('name')
  467. if like_cnt == "" or like_cnt == "喜欢" or like_cnt == "火" or cls.is_contain_chinese(like_cnt) is True:
  468. like_cnt = 0
  469. elif '万' in like_cnt:
  470. like_cnt = int(float(like_cnt.split('万')[0]) * 10000)
  471. elif '万+' in like_cnt:
  472. like_cnt = int(float(like_cnt.split('万+')[0]) * 10000)
  473. else:
  474. like_cnt = int(float(like_cnt))
  475. # 分享
  476. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  477. share_cnt = share_id.get_attribute('name')
  478. if share_cnt == "" or share_cnt == "转发" or cls.is_contain_chinese(share_cnt) is True:
  479. share_cnt = 0
  480. elif '万' in share_cnt:
  481. share_cnt = int(float(share_cnt.split('万')[0]) * 10000)
  482. elif '万+' in share_cnt:
  483. share_cnt = int(float(share_cnt.split('万+')[0]) * 10000)
  484. else:
  485. share_cnt = int(float(share_cnt))
  486. # 收藏
  487. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  488. favorite_cnt = favorite_id.get_attribute('name')
  489. if favorite_cnt == "" or favorite_cnt == "收藏" or favorite_cnt == "推荐" or favorite_cnt == "火" or cls.is_contain_chinese(favorite_cnt) is True:
  490. favorite_cnt = 0
  491. elif '万' in favorite_cnt:
  492. favorite_cnt = int(float(favorite_cnt.split('万')[0]) * 10000)
  493. elif '万+' in favorite_cnt:
  494. favorite_cnt = int(float(favorite_cnt.split('万+')[0]) * 10000)
  495. else:
  496. favorite_cnt = int(float(favorite_cnt))
  497. # 评论
  498. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  499. comment_cnt = comment_id.get_attribute('name')
  500. if comment_cnt == "" or comment_cnt == "评论" or cls.is_contain_chinese(comment_cnt) is True:
  501. comment_cnt = 0
  502. elif '万' in comment_cnt:
  503. comment_cnt = int(float(comment_cnt.split('万')[0]) * 10000)
  504. elif '万+' in comment_cnt:
  505. comment_cnt = int(float(comment_cnt.split('万+')[0]) * 10000)
  506. else:
  507. comment_cnt = int(float(comment_cnt))
  508. # 发布时间
  509. comment_id.click()
  510. time.sleep(1)
  511. publish_time = driver.find_element(By.ID, "com.tencent.mm:id/bre").get_attribute("name")
  512. if "秒" in publish_time or "分钟" in publish_time or "小时" in publish_time:
  513. publish_time_str = (date.today() + timedelta(days=0)).strftime("%Y-%m-%d")
  514. elif "天前" in publish_time:
  515. days = int(publish_time.replace("天前", ""))
  516. publish_time_str = (date.today() + timedelta(days=-days)).strftime("%Y-%m-%d")
  517. elif "年" in publish_time:
  518. # publish_time_str = publish_time.replace("年", "-").replace("月", "-").replace("日", "")
  519. year_str = publish_time.split("年")[0]
  520. month_str = publish_time.split("年")[-1].split("月")[0]
  521. day_str = publish_time.split("月")[-1].split("日")[0]
  522. if int(month_str) < 10:
  523. month_str = f"0{month_str}"
  524. if int(day_str) < 10:
  525. day_str = f"0{day_str}"
  526. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  527. else:
  528. year_str = str(datetime.datetime.now().year)
  529. month_str = publish_time.split("月")[0]
  530. day_str = publish_time.split("月")[-1].split("日")[0]
  531. if int(month_str) < 10:
  532. month_str = f"0{month_str}"
  533. if int(day_str) < 10:
  534. day_str = f"0{day_str}"
  535. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  536. # publish_time_str = f'2023-{publish_time.replace("月", "-").replace("日", "")}'
  537. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y-%m-%d")))
  538. # 收起评论
  539. # Common.logger(log_type, crawler).info("收起评论")
  540. driver.find_element(By.ID, "com.tencent.mm:id/be_").click()
  541. time.sleep(0.5)
  542. # 返回 webview
  543. # Common.logger(log_type, crawler).info(f"操作手机返回按键")
  544. driver.find_element(By.ID, "com.tencent.mm:id/a2z").click()
  545. time.sleep(0.5)
  546. # driver.press_keycode(AndroidKey.BACK)
  547. # cls.check_to_webview(log_type=log_type, crawler=crawler, driver=driver)
  548. webviews = driver.contexts
  549. driver.switch_to.context(webviews[1])
  550. video_dict = {
  551. "like_cnt": like_cnt,
  552. "share_cnt": share_cnt,
  553. "favorite_cnt": favorite_cnt,
  554. "comment_cnt": comment_cnt,
  555. "publish_time_str": publish_time_str,
  556. "publish_time_stamp": publish_time_stamp,
  557. }
  558. return video_dict
  559. @classmethod
  560. def get_users(cls, log_type, crawler, sheetid, env):
  561. while True:
  562. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  563. if user_sheet is None:
  564. Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 3秒钟后重试")
  565. time.sleep(3)
  566. continue
  567. our_user_list = []
  568. for i in range(1, len(user_sheet)):
  569. # for i in range(1, 3):
  570. search_word = user_sheet[i][4]
  571. our_uid = user_sheet[i][6]
  572. tag1 = user_sheet[i][8]
  573. tag2 = user_sheet[i][9]
  574. tag3 = user_sheet[i][10]
  575. tag4 = user_sheet[i][11]
  576. tag5 = user_sheet[i][12]
  577. Common.logger(log_type, crawler).info(f"正在更新 {search_word} 搜索词信息")
  578. if our_uid is None:
  579. default_user = getUser.get_default_user()
  580. # 用来创建our_id的信息
  581. user_dict = {
  582. 'recommendStatus': -6,
  583. 'appRecommendStatus': -6,
  584. 'nickName': default_user['nickName'],
  585. 'avatarUrl': default_user['avatarUrl'],
  586. 'tagName': f'{tag1},{tag2},{tag3},{tag4},{tag5}',
  587. }
  588. our_uid = getUser.create_uid(log_type, crawler, user_dict, env)
  589. if env == 'prod':
  590. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  591. else:
  592. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  593. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}',
  594. [[our_uid, our_user_link]])
  595. Common.logger(log_type, crawler).info(f'站内用户主页创建成功:{our_user_link}\n')
  596. our_user_dict = {
  597. 'out_uid': '',
  598. 'search_word': search_word,
  599. 'our_uid': our_uid,
  600. 'our_user_link': f'https://admin.piaoquantv.com/ums/user/{our_uid}/post',
  601. }
  602. our_user_list.append(our_user_dict)
  603. return our_user_list
  604. @classmethod
  605. def get_search_videos(cls, log_type, crawler, env):
  606. user_list = cls.get_users(log_type, crawler, "wNgi6Z", env)
  607. for user in user_list:
  608. cls.i = 0
  609. cls.download_cnt = 0
  610. search_word = user["search_word"]
  611. our_uid = user["our_uid"]
  612. Common.logger(log_type, crawler).info(f"开始抓取搜索词:{search_word}")
  613. # try:
  614. cls.start_wechat(log_type=log_type,
  615. crawler=crawler,
  616. word=search_word,
  617. our_uid=our_uid,
  618. env=env)
  619. # except Exception as e:
  620. # Common.logger(log_type, crawler).error(f"search_video:{e}\n")
  621. if __name__ == '__main__':
  622. # ShipinhaoSearchScheduling.get_search_videos(log_type="search",
  623. # crawler="shipinhao",
  624. # 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}}]',
  625. # oss_endpoint="out",
  626. # env="dev")
  627. # print(ShipinhaoSearchScheduling.get_users("search", "shipinhao", "wNgi6Z", "dev"))
  628. # print((date.today() + timedelta(days=0)).strftime("%Y-%m-%d"))
  629. # print(ShipinhaoSearchScheduling.repeat_out_video_id(log_type="search",
  630. # crawler="shipinhao",
  631. # out_video_id="123",
  632. # env="dev"))
  633. # ShipinhaoSearch.download_rule(log_type="search", crawler="shipinhao", video_dict={})
  634. print(ShipinhaoSearch.rule_dict(log_type="search", crawler="shipinhao"))
  635. pass