shipinhao_search.py 41 KB

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