login_ad.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from selenium import webdriver
  2. from selenium.webdriver import ActionChains
  3. from selenium.webdriver.common.by import By
  4. from selenium.webdriver.support import expected_conditions as EC
  5. from selenium.webdriver.support.wait import WebDriverWait
  6. from wechat_action.create_ad_plan_idea import IdeaAction
  7. from wechat_action.human_ad import HumanAd
  8. from selenium.webdriver import ChromeOptions
  9. from selenium.webdriver.common.keys import Keys
  10. from sqlalchemy import Table
  11. from wechat_action import sql_tools
  12. import time
  13. import pickle
  14. from settings import using_config
  15. from wechat_action.sql_models import DB
  16. import requests
  17. import json
  18. import logging
  19. import re
  20. class LogIn:
  21. # TODO:整体运行使用逻辑,需要修改几次
  22. def __init__(self, user_id):
  23. # 获取到单独服务商下的独立公众号页面
  24. self.user_id = user_id
  25. self.driver = self.get_driver()
  26. self.db = DB(config=using_config)
  27. self.wechat_cookies_table = Table('wechat_cookies', self.db.metadata,
  28. autoload=True, autoload_with=self.db.engine)
  29. # self.log_in()
  30. # self.select_ad_master()
  31. def get_driver(self):
  32. options = ChromeOptions()
  33. # 防止selenium快速崩坏
  34. options.add_argument("--disable-dev-shm-usage")
  35. options.add_experimental_option('excludeSwitches', ['enable-automation'])
  36. # prefs = {"profile.managed_default_content_settings.images": 2, 'permissions.default.stylesheet': 2}
  37. # options.add_experimental_option("prefs", prefs)
  38. driver = webdriver.Remote(
  39. # command_executor='http://192.168.1.100/wd/hub',
  40. command_executor='http://118.31.53.105:4555/wd/hub',
  41. options=options)
  42. # driver = webdriver.Chrome(options=options)
  43. driver.maximize_window()
  44. return driver
  45. def log_in(self):
  46. # self.wechat_cookie_use()
  47. logging.info('开始登录')
  48. self.driver.get('https://a.weixin.qq.com/index.html')
  49. img_selector = 'body > div.old-template > div > div > div.waiting.panelContent > div.wrp_code > img'
  50. frame_login = self.driver.find_element_by_xpath('//*[@id="login_container"]/iframe')
  51. self.driver.switch_to.frame(frame_login)
  52. # WebDriverWait(driver, 3).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, img_selector)))
  53. # time.sleep(3)
  54. img_url = self.driver.find_element_by_css_selector(img_selector)
  55. return img_url.get_attribute('src')
  56. def log_in_wait(self):
  57. # 默认等待6分钟
  58. WebDriverWait(self.driver, 6 * 60).until(lambda driver: self.driver.find_elements_by_link_text('广告投放'))
  59. logging.info('登录成功')
  60. @staticmethod
  61. def cookies_save(log_ad, sql_session):
  62. logging.info('update db cookie')
  63. # 切换窗口,点击创建广告,切到广告页面
  64. log_ad.driver.switch_to.window(log_ad.driver.window_handles[0])
  65. WebDriverWait(log_ad.driver, 100).until(lambda driver: driver.find_element_by_class_name(
  66. 'ui-mr-medium'))
  67. wechat_cookies, wechat_id_tmp = log_ad.wechat_cookie_pickle()
  68. wechat_id = sql_tools.get_wechat_id_from_cookies(log_ad.user_id, sql_session)
  69. if wechat_id:
  70. if wechat_id_tmp != wechat_id:
  71. raise ValueError("微信账号,非以前老账号,登录失败")
  72. # cookie 进行数据库保存
  73. update_res = log_ad.wechat_cookies_table.update() \
  74. .where(log_ad.wechat_cookies_table.c.user_id == log_ad.user_id) \
  75. .values(cookies=wechat_cookies,
  76. scan_action='done')
  77. sql_session.execute(update_res)
  78. sql_session.commit()
  79. else:
  80. wechat_cookies_info = {'user_id': log_ad.user_id, 'cookies': wechat_cookies, 'scan_action': 'done'}
  81. wechat_insert = sql_tools.save_wechat_cookies(wechat_cookies_info=wechat_cookies_info,
  82. table_wechat_cookies=log_ad.wechat_cookies_table)
  83. sql_session.execute(wechat_insert)
  84. sql_session.commit()
  85. log_ad.driver.switch_to.window(log_ad.driver.window_handles[-1])
  86. def select_ad_master(self, service_name, wechat_name, sql_session):
  87. logging.info('开始切换服务商')
  88. time.sleep(5)
  89. self.driver.execute_script('''
  90. window.scroll(0,1000000);
  91. ''')
  92. self.driver.find_element_by_css_selector(
  93. '#root > div > header > div > div.CoreLayout__account-2lIr0 > div').click()
  94. self.driver.find_element_by_css_selector(
  95. '#root > div > div.CoreLayout__headerDropdown-3xWkD > div > div:nth-child(1) > button').click()
  96. service_names = self.driver.find_elements_by_class_name('CoreLayout__headerDropdownItem-X4S98')
  97. choice_service = None
  98. for _ in service_names:
  99. if service_name in _.text:
  100. choice_service = _
  101. choice_service.click()
  102. # 挑选广告投放位置
  103. time.sleep(3)
  104. input_wechat_name = self.driver.find_element_by_class_name('TextInput_new__iconRight-pekjS')
  105. input_wechat_name.click()
  106. input_wechat_name.send_keys(wechat_name)
  107. input_wechat_name.send_keys(Keys.RETURN)
  108. self.driver.execute_script('''
  109. window.scroll(100000,1000000);
  110. var e_one=document.getElementsByClassName('Table_new__wrapper-1cpZN')[0];
  111. e_one.scroll(10000,100000);
  112. ''')
  113. time.sleep(5)
  114. elements = self.driver.find_elements_by_link_text('广告投放')
  115. elements[0].click()
  116. time.sleep(1)
  117. logging.info('切换服务商成功')
  118. self.cookies_save(self, sql_session)
  119. @staticmethod
  120. def get_cookie(driver, login_cookie=True):
  121. if login_cookie:
  122. WebDriverWait(driver, 100).until(
  123. lambda x: [True for _ in driver.get_cookies() if 'token_ticket' == _['name']]
  124. )
  125. cookies = driver.get_cookies()
  126. cookie_dict = {}
  127. for _ in cookies:
  128. cookie_dict[_['name']] = _['value']
  129. return cookie_dict
  130. def wechat_cookie_pickle(self):
  131. wechat_id = None
  132. self.driver.get('https://a.weixin.qq.com/client')
  133. WebDriverWait(self.driver, 100).until(
  134. lambda x: [True for _ in self.driver.get_cookies() if 'token_ticket' == _['name']]
  135. )
  136. WebDriverWait(self.driver, 100).until(
  137. lambda x: re.findall('g_tk=(\d+)&', self.driver.page_source)
  138. )
  139. cookies = self.driver.get_cookies()
  140. cookies_obj = pickle.dumps(cookies)
  141. g_tk = re.findall('g_tk=(\d+)&', self.driver.page_source)[0]
  142. wechat_cookies = self.get_cookie(self.driver)
  143. wechat_url = 'https://a.weixin.qq.com/cgi-bin/agency/check_login?g_tk={g_tk}&_={time_p}'.format(g_tk=g_tk,
  144. time_p=int(
  145. time.time() * 1000))
  146. rsp = requests.get(url=wechat_url, cookies=wechat_cookies)
  147. wechat_id = rsp.json()['data'][0]['wx_id']
  148. return cookies_obj, wechat_id
  149. def wechat_cookies_check_alive(self, driver_cookies):
  150. # wechat 检查cookies 是否可用
  151. # 可用返回ture
  152. check_url = 'https://a.weixin.qq.com/cgi-bin/agency/get_delivery_metrics?page=1&page_size=10&search_key=&order_by=&ascending=1&only_collect=0&g_tk=5381&_={}'.format(
  153. int(time.time() * 1000))
  154. # cookie_dict = {}
  155. # for _ in driver_cookies:
  156. # cookie_dict[_['name']] = _['value']
  157. # rsp_json = requests.get(url=check_url, cookies=cookie_dict).json()
  158. self.driver.get('https://www.baidu.com')
  159. self.driver.get('https://a.weixin.qq.com/client')
  160. for _ in driver_cookies:
  161. self.driver.add_cookie(_)
  162. self.driver.get('https://a.weixin.qq.com/client')
  163. self.driver.get(check_url)
  164. if '4101' in self.driver.page_source:
  165. return False
  166. else:
  167. return True
  168. def upadte_user_info(self):
  169. # TODO: 更新 用户相关信息
  170. # 每次登录就更新一次相关数据,------公众号相关数据,人群报相关数据
  171. pass
  172. def get_driver_loged(self):
  173. return self.driver
  174. def refresh_driver(self):
  175. err_num = 0
  176. logging.info('开始刷新chrome')
  177. while True:
  178. try:
  179. if len(self.driver.window_handles) > 1:
  180. self.driver.switch_to.window(self.driver.window_handles[-1])
  181. self.driver.execute_script('window.close();')
  182. time.sleep(1)
  183. # 规避有弹窗的情况
  184. self.driver.switch_to.alert.accept()
  185. else:
  186. self.driver.switch_to.window(self.driver.window_handles[-1])
  187. self.driver.get('https://a.weixin.qq.com')
  188. break
  189. except Exception as e:
  190. logging.error(e)
  191. err_num = err_num + 1
  192. if err_num > 3:
  193. break
  194. logging.info('刷新chrome 结束')