shipinhao_search.py 36 KB

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