login_ad.py 8.3 KB

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