shipinhao_search.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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_v86/chromedriver"
  27. else:
  28. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  29. caps = {
  30. "platformName": "Android", # 手机操作系统 Android / iOS
  31. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  32. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  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. time.sleep(5)
  55. # 根据词搜索视频
  56. cls.search_video(log_type=log_type,
  57. crawler=crawler,
  58. driver=driver,
  59. sheetid=sheetid,
  60. env=env)
  61. # except Exception as e:
  62. # Common.logger(log_type, crawler).error('start_wechat异常,重启APP:{}\n', e)
  63. # 查找元素
  64. @classmethod
  65. def search_elements(cls, driver: WebDriver, xpath):
  66. time.sleep(1)
  67. windowHandles = driver.window_handles
  68. for handle in windowHandles:
  69. driver.switch_to.window(handle)
  70. time.sleep(1)
  71. try:
  72. elements = driver.find_elements(By.XPATH, xpath)
  73. if elements:
  74. return elements
  75. except NoSuchElementException:
  76. pass
  77. @classmethod
  78. def check_to_webview(cls, log_type, crawler, driver: WebDriver):
  79. while True:
  80. Common.logger(log_type, crawler).info('切换到webview')
  81. webview = driver.contexts
  82. driver.switch_to.context(webview[1])
  83. @classmethod
  84. def search_video(cls, log_type, crawler, driver: WebDriver, sheetid, env):
  85. word_list = get_config_from_mysql(log_type, crawler, env, "search_word", action="")
  86. for word in word_list:
  87. driver.implicitly_wait(10)
  88. Common.logger(log_type, crawler).info('点击搜索按钮')
  89. driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()
  90. time.sleep(0.5)
  91. Common.logger(log_type, crawler).info(f'输入视频标题:{word}')
  92. driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)
  93. Common.logger(log_type, crawler).info('点击搜索')
  94. driver.press_keycode(AndroidKey.ENTER)
  95. driver.find_elements(By.ID, 'com.tencent.mm:id/oi4')[0].click()
  96. cls.check_to_webview(log_type, crawler, driver)
  97. video_list = cls.search_elements(driver, '//div[@class="unit"]/*[2]')
  98. Common.logger(log_type, crawler).info('点击"视频号"分类')
  99. video_list[0].click()
  100. time.sleep(5)
  101. index = 0
  102. while True:
  103. if index == 30:
  104. Common.logger(log_type, crawler).info(f'"{word}"已抓取视频数:{index}\n')
  105. break
  106. try:
  107. if cls.search_elements(driver, '//*[@class="double-rich double-rich_vertical"]') is None:
  108. Common.logger(log_type, crawler).info('窗口已销毁\n')
  109. return
  110. Common.logger(log_type, crawler).info('获取视频列表\n')
  111. video_elements = cls.search_elements(driver, '//wx-view[@class="double-rich double-rich_vertical"]')
  112. if video_elements is None:
  113. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  114. return
  115. video_element_temp = video_elements[index:]
  116. if len(video_element_temp) == 0:
  117. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  118. return
  119. for i, video_element in enumerate(video_element_temp):
  120. if video_element is None:
  121. Common.logger(log_type, crawler).info('到底啦~\n')
  122. return
  123. cls.i += 1
  124. cls.search_elements(driver, '//wx-view[@"double-rich double-rich_vertical"]')
  125. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  126. time.sleep(3)
  127. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
  128. video_element)
  129. Common.logger(log_type, crawler).info("点击进入视频详情")
  130. video_element.click()
  131. time.sleep(3)
  132. cls.get_video_info(log_type=log_type,
  133. crawler=crawler,
  134. driver=driver,
  135. sheetid=sheetid)
  136. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  137. time.sleep(10)
  138. index = index + len(video_element_temp)
  139. except Exception as e:
  140. Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  141. cls.i = 0
  142. @classmethod
  143. def get_video_info(cls, log_type, crawler, driver: WebDriver, sheetid):
  144. # webview = driver.contexts
  145. Common.logger(log_type, crawler).info('切回NATIVE_APP\n')
  146. driver.switch_to.context('NATIVE_APP')
  147. # 点击播放器,获取视频时长
  148. # Common.logger(log_type, crawler).info('暂停播放')
  149. pause_btn = driver.find_element(By.ID, 'com.tencent.mm:id/eh4')
  150. pause_btn.click()
  151. start_time = driver.find_element(By.ID, 'com.tencent.mm:id/l59').get_attribute('name')
  152. start_time = int(start_time.split(':')[0]) * 60 + int(start_time.split(':')[-1])
  153. try:
  154. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/l7i').get_attribute('name')
  155. except NoSuchElementException:
  156. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/g73').get_attribute('name')
  157. end_time = int(end_time.split(':')[0]) * 60 + int(end_time.split(':')[-1])
  158. duration = start_time + end_time
  159. # 点赞
  160. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  161. like_cnt = like_id.get_attribute('name')
  162. if like_cnt == "" or like_cnt == "喜欢":
  163. like_cnt = 0
  164. elif '万' in like_cnt:
  165. like_cnt = float(like_cnt.split('万')[0]) * 10000
  166. elif '万+' in like_cnt:
  167. like_cnt = float(like_cnt.split('万+')[0]) * 10000
  168. else:
  169. like_cnt = float(like_cnt)
  170. # 分享
  171. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  172. share_cnt = share_id.get_attribute('name')
  173. if share_cnt == "" or share_cnt == "转发":
  174. share_cnt = 0
  175. elif '万' in share_cnt:
  176. share_cnt = float(share_cnt.split('万')[0]) * 10000
  177. elif '万+' in share_cnt:
  178. share_cnt = float(share_cnt.split('万+')[0]) * 10000
  179. else:
  180. share_cnt = float(share_cnt)
  181. # 收藏
  182. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  183. favorite_cnt = favorite_id.get_attribute('name')
  184. if favorite_cnt == "" or favorite_cnt == "收藏":
  185. favorite_cnt = 0
  186. elif '万' in favorite_cnt:
  187. favorite_cnt = float(favorite_cnt.split('万')[0]) * 10000
  188. elif '万+' in favorite_cnt:
  189. favorite_cnt = float(favorite_cnt.split('万+')[0]) * 10000
  190. else:
  191. favorite_cnt = float(favorite_cnt)
  192. # 评论
  193. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  194. comment_cnt = comment_id.get_attribute('name')
  195. if comment_cnt == "" or comment_cnt == "评论":
  196. comment_cnt = 0
  197. elif '万' in comment_cnt:
  198. comment_cnt = float(comment_cnt.split('万')[0]) * 10000
  199. elif '万+' in comment_cnt:
  200. comment_cnt = float(comment_cnt.split('万+')[0]) * 10000
  201. else:
  202. comment_cnt = float(comment_cnt)
  203. # 把视频信息写入飞书feeds文档
  204. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  205. "视频号搜索",
  206. "标题",
  207. duration,
  208. like_cnt,
  209. share_cnt,
  210. favorite_cnt,
  211. comment_cnt]]
  212. time.sleep(1)
  213. Feishu.update_values(log_type, crawler, sheetid, 'F2:Z2', values)
  214. Common.logger(log_type, crawler).info('视频信息写入飞书文档成功\n')
  215. if __name__ == '__main__':
  216. ShipinhaoSearch.start_wechat(log_type="search",
  217. crawler="shipinhao",
  218. sheetid="xYWCzf",
  219. env="dev")
  220. pass