shipinhao_search.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/25
  4. import difflib
  5. import os
  6. import sys
  7. import time
  8. from hashlib import md5
  9. from appium import webdriver
  10. from appium.webdriver.extensions.android.nativekey import AndroidKey
  11. from appium.webdriver.webdriver import WebDriver
  12. from selenium.common import NoSuchElementException
  13. from selenium.webdriver.common.by import By
  14. sys.path.append(os.getcwd())
  15. from common.feishu import Feishu
  16. from common.publish import Publish
  17. from common.common import Common
  18. from common.public import get_config_from_mysql
  19. class ShipinhaoSearch:
  20. i = 0
  21. @classmethod
  22. def start_wechat(cls, log_type, crawler, sheetid, env):
  23. # try:
  24. Common.logger(log_type, crawler).info('启动微信')
  25. if env == "dev":
  26. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver"
  27. else:
  28. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  29. caps = {
  30. "platformName": "Android", # 手机操作系统 Android / iOS
  31. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  32. "platforVersion": "13", # 手机对应的系统版本(Android 13)
  33. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  34. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  35. "autoGrantPermissions": True, # 让 appium 自动授权 base 权限,
  36. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  37. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  38. "resetkeyboard": True, # 执行完程序恢复原来输入法
  39. "noReset": True, # 不重置APP
  40. "recreateChromeDriverSessions": True, # 切换到非 chrome-Driver 会 kill 掉 session,就不需要手动 kill 了
  41. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  42. "newCommandTimeout": 6000, # 初始等待时间
  43. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  44. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  45. "showChromedriverLog": True,
  46. # "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  47. "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  48. 'enableWebviewDetailsCollection': True,
  49. 'setWebContentsDebuggingEnabled': True,
  50. 'chromedriverExecutable': chromedriverExecutable,
  51. }
  52. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  53. driver.implicitly_wait(10)
  54. if len(driver.find_elements(By.ID, 'android:id/text1')) != 0:
  55. driver.find_elements(By.ID, 'android:id/text1')[0].click()
  56. time.sleep(5)
  57. # 根据词搜索视频
  58. cls.search_video(log_type=log_type,
  59. crawler=crawler,
  60. driver=driver,
  61. env=env)
  62. # except Exception as e:
  63. # Common.logger(log_type, crawler).error('start_wechat异常,重启APP:{}\n', e)
  64. # 查找元素
  65. @classmethod
  66. def search_elements(cls, driver: WebDriver, xpath):
  67. time.sleep(1)
  68. windowHandles = driver.window_handles
  69. for handle in windowHandles:
  70. driver.switch_to.window(handle)
  71. time.sleep(1)
  72. try:
  73. elements = driver.find_elements(By.XPATH, xpath)
  74. if elements:
  75. return elements
  76. except NoSuchElementException:
  77. pass
  78. @classmethod
  79. def check_to_webview(cls, log_type, crawler, driver: WebDriver):
  80. Common.logger(log_type, crawler).info('切换到webview')
  81. webviews = driver.contexts
  82. # Common.logger(log_type, crawler).info(f"webview:{webviews}")
  83. driver.switch_to.context(webviews[1])
  84. time.sleep(1)
  85. windowHandles = driver.window_handles
  86. for handle in windowHandles:
  87. driver.switch_to.window(handle)
  88. try:
  89. shipinhao_webview = driver.find_element(By.XPATH, '//div[@class="unit11111"]')
  90. if shipinhao_webview:
  91. Common.logger(log_type, crawler).info('切换到视频号 webview 成功\n')
  92. return "成功"
  93. except Exception as e:
  94. Common.logger(log_type, crawler).info(f"{e}\n")
  95. # return None
  96. @classmethod
  97. def search_video(cls, log_type, crawler, driver: WebDriver, env):
  98. word_list = get_config_from_mysql(log_type, crawler, env, "search_word", action="")
  99. for word in word_list:
  100. driver.implicitly_wait(10)
  101. Common.logger(log_type, crawler).info('点击搜索按钮')
  102. driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()
  103. time.sleep(0.5)
  104. Common.logger(log_type, crawler).info(f'输入搜索词:{word}')
  105. driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)
  106. Common.logger(log_type, crawler).info('点击搜索')
  107. driver.press_keycode(AndroidKey.ENTER)
  108. # driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  109. driver.find_element(By.ID, 'com.tencent.mm:id/m94').click()
  110. time.sleep(5)
  111. check_to_webview = cls.check_to_webview(log_type, crawler, driver)
  112. if check_to_webview is None:
  113. Common.logger(log_type, crawler).info("切换到视频号 webview 失败\n")
  114. return
  115. # Common.logger(log_type, crawler).info('切换到webview')
  116. # webviews = driver.contexts
  117. # Common.logger(log_type, crawler).info(f"webview:{webviews}")
  118. # driver.switch_to.context(webviews[1])
  119. # driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')
  120. # Common.logger(log_type, crawler).info(f"{driver.page_source}")
  121. # Common.logger(log_type, crawler).info('切换到webview')
  122. # webview = driver.contexts
  123. # driver.switch_to.context(webview[1])
  124. # time.sleep(5)
  125. # video_list = cls.search_elements(driver, '//div[@class="unit"]/*[2]')
  126. # Common.logger(log_type, crawler).info('点击"视频"分类')
  127. # video_list[0].click()
  128. # time.sleep(5)
  129. #
  130. # video_list = cls.search_elements(driver, '//div[@class="unit"]/*[2]')
  131. # Common.logger(log_type, crawler).info(f"video_list:{video_list}")
  132. # Common.logger(log_type, crawler).info('点击"视频号"分类')
  133. # video_list[0].click()
  134. # time.sleep(5)
  135. #
  136. # index = 0
  137. # while True:
  138. # if index == 30:
  139. # Common.logger(log_type, crawler).info(f'"{word}"已抓取视频数:{index}\n')
  140. # break
  141. # try:
  142. # if cls.search_elements(driver, '//*[@class="double-rich double-rich_vertical"]') is None:
  143. # Common.logger(log_type, crawler).info('窗口已销毁\n')
  144. # return
  145. #
  146. # Common.logger(log_type, crawler).info('获取视频列表\n')
  147. # video_elements = cls.search_elements(driver, '//wx-view[@class="double-rich double-rich_vertical"]')
  148. # if video_elements is None:
  149. # Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  150. # return
  151. #
  152. # video_element_temp = video_elements[index:]
  153. # if len(video_element_temp) == 0:
  154. # Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  155. # return
  156. #
  157. # for i, video_element in enumerate(video_element_temp):
  158. # if video_element is None:
  159. # Common.logger(log_type, crawler).info('到底啦~\n')
  160. # return
  161. # cls.i += 1
  162. # cls.search_elements(driver, '//wx-view[@"double-rich double-rich_vertical"]')
  163. #
  164. # Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  165. # time.sleep(3)
  166. # driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
  167. # video_element)
  168. # Common.logger(log_type, crawler).info("点击进入视频详情")
  169. # video_element.click()
  170. # time.sleep(3)
  171. # cls.get_video_info(log_type=log_type,
  172. # crawler=crawler,
  173. # driver=driver,
  174. # sheetid=sheetid)
  175. # Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  176. # time.sleep(10)
  177. # index = index + len(video_element_temp)
  178. # except Exception as e:
  179. # Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  180. # cls.i = 0
  181. @classmethod
  182. def get_video_info(cls, log_type, crawler, driver: WebDriver, sheetid):
  183. # webview = driver.contexts
  184. Common.logger(log_type, crawler).info('切回NATIVE_APP\n')
  185. driver.switch_to.context('NATIVE_APP')
  186. # 点击播放器,获取视频时长
  187. # Common.logger(log_type, crawler).info('暂停播放')
  188. pause_btn = driver.find_element(By.ID, 'com.tencent.mm:id/eh4')
  189. pause_btn.click()
  190. start_time = driver.find_element(By.ID, 'com.tencent.mm:id/l59').get_attribute('name')
  191. start_time = int(start_time.split(':')[0]) * 60 + int(start_time.split(':')[-1])
  192. try:
  193. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/l7i').get_attribute('name')
  194. except NoSuchElementException:
  195. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/g73').get_attribute('name')
  196. end_time = int(end_time.split(':')[0]) * 60 + int(end_time.split(':')[-1])
  197. duration = start_time + end_time
  198. # 点赞
  199. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  200. like_cnt = like_id.get_attribute('name')
  201. if like_cnt == "" or like_cnt == "喜欢":
  202. like_cnt = 0
  203. elif '万' in like_cnt:
  204. like_cnt = float(like_cnt.split('万')[0]) * 10000
  205. elif '万+' in like_cnt:
  206. like_cnt = float(like_cnt.split('万+')[0]) * 10000
  207. else:
  208. like_cnt = float(like_cnt)
  209. # 分享
  210. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  211. share_cnt = share_id.get_attribute('name')
  212. if share_cnt == "" or share_cnt == "转发":
  213. share_cnt = 0
  214. elif '万' in share_cnt:
  215. share_cnt = float(share_cnt.split('万')[0]) * 10000
  216. elif '万+' in share_cnt:
  217. share_cnt = float(share_cnt.split('万+')[0]) * 10000
  218. else:
  219. share_cnt = float(share_cnt)
  220. # 收藏
  221. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  222. favorite_cnt = favorite_id.get_attribute('name')
  223. if favorite_cnt == "" or favorite_cnt == "收藏":
  224. favorite_cnt = 0
  225. elif '万' in favorite_cnt:
  226. favorite_cnt = float(favorite_cnt.split('万')[0]) * 10000
  227. elif '万+' in favorite_cnt:
  228. favorite_cnt = float(favorite_cnt.split('万+')[0]) * 10000
  229. else:
  230. favorite_cnt = float(favorite_cnt)
  231. # 评论
  232. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  233. comment_cnt = comment_id.get_attribute('name')
  234. if comment_cnt == "" or comment_cnt == "评论":
  235. comment_cnt = 0
  236. elif '万' in comment_cnt:
  237. comment_cnt = float(comment_cnt.split('万')[0]) * 10000
  238. elif '万+' in comment_cnt:
  239. comment_cnt = float(comment_cnt.split('万+')[0]) * 10000
  240. else:
  241. comment_cnt = float(comment_cnt)
  242. # 把视频信息写入飞书feeds文档
  243. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  244. "视频号搜索",
  245. "标题",
  246. duration,
  247. like_cnt,
  248. share_cnt,
  249. favorite_cnt,
  250. comment_cnt]]
  251. time.sleep(1)
  252. Feishu.update_values(log_type, crawler, sheetid, 'F2:Z2', values)
  253. Common.logger(log_type, crawler).info('视频信息写入飞书文档成功\n')
  254. if __name__ == '__main__':
  255. ShipinhaoSearch.start_wechat(log_type="search",
  256. crawler="shipinhao",
  257. sheetid="xYWCzf",
  258. env="dev")
  259. pass