create_ad_layout.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. from selenium.webdriver.support.wait import WebDriverWait
  2. from selenium.webdriver.common.keys import Keys
  3. from selenium.webdriver import ActionChains
  4. from logging import handlers
  5. import logging
  6. import requests
  7. import random
  8. import shutil
  9. import time
  10. import re
  11. import os
  12. class CreateAd:
  13. def __init__(self, login_ad, service_name, wechat_name):
  14. self.log_ad = login_ad
  15. self.service_name = service_name
  16. self.wechat_name = wechat_name
  17. self.driver = login_ad.get_driver_loged()
  18. self.get_into_create_page()
  19. self.send_file_limit_num = 8
  20. self.img_dir = './img'
  21. def get_into_create_page(self):
  22. # 进入创建页面
  23. self.driver.find_element_by_id('material').click()
  24. try:
  25. # 落地页内容有的账户有,有的无,无的默认等5s
  26. WebDriverWait(self.driver, 5).until(lambda driver: len(self.driver.find_elements_by_xpath(
  27. '//*[@class="adui-table-cell"]')))
  28. for i in self.driver.find_elements_by_xpath(
  29. '//*[@class="adui-table-cell"]'):
  30. WebDriverWait(self.driver, 5).until(lambda driver: i.is_displayed() and i.is_enabled())
  31. except Exception as e:
  32. logging.error(str(e))
  33. time.sleep(5)
  34. WebDriverWait(self.driver, 10).until(lambda driver: self.driver.find_element_by_xpath(
  35. '//*[@class="ui-fl-r adui-button-base adui-button-primary adui-button-small"]'))
  36. create_element = self.driver.find_element_by_xpath(
  37. '//*[@class="ui-fl-r adui-button-base adui-button-primary adui-button-small"]')
  38. WebDriverWait(self.driver, 10).until(
  39. lambda driver: create_element.is_displayed() and create_element.is_enabled())
  40. create_element.click()
  41. logging.info('点击新建推广页 结束')
  42. WebDriverWait(self.driver, 5).until(lambda driver: driver.find_element_by_css_selector(
  43. '#wxadcontainer > div:nth-child(1) > div:nth-child(2) > div.dialog-1fj_N480ZT > div > div > div:nth-child(1) > div.dialogCardFooter-17KpBD1lgN > button'))
  44. self.driver.find_element_by_css_selector(
  45. '#wxadcontainer > div:nth-child(1) > div:nth-child(2) > div.dialog-1fj_N480ZT > div > div > div:nth-child(1) > div.dialogCardFooter-17KpBD1lgN > button').click()
  46. self.driver.switch_to.window(self.driver.window_handles[-1])
  47. WebDriverWait(self.driver, 100).until(lambda driver: driver.find_element_by_class_name('addContent-8pexaaAGYy'))
  48. self.driver.find_element_by_class_name('addContent-8pexaaAGYy').click()
  49. WebDriverWait(self.driver, 100).until(lambda driver: driver.find_element_by_class_name('topArea-qOwEAeNuIn'))
  50. logging.info('进入到推广页,编辑界面')
  51. def set_advertisement_sign(self, layout_name):
  52. # 设置广告标记
  53. self.driver.find_element_by_xpath('//*[@class="icon-edQB0KK2VG"]').click()
  54. input_element = self.driver.find_element_by_xpath('//input[@class="input-2lFnByGCRh"]')
  55. input_element.send_keys(Keys.BACKSPACE)
  56. input_element.send_keys(layout_name)
  57. def set_background_color(self, color):
  58. color_buttons = self.driver.find_elements_by_class_name('adui-cp-picker')
  59. c_buttons_can_use = []
  60. for _ in color_buttons:
  61. if _.is_displayed() and _.is_enabled():
  62. c_buttons_can_use.append(_)
  63. c_buttons_can_use[0].click()
  64. time.sleep(random.uniform(0.2, 0.3))
  65. input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  66. for _ in input_elements:
  67. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == 'FFFFFF':
  68. _.click()
  69. _.send_keys(color)
  70. def set_head_assemb(self, info):
  71. logging.info('开始设置头版首页')
  72. def single_page_set():
  73. self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/div[1]/div/div[1]/div/div').click()
  74. time.sleep(random.uniform(0.1, 0.2))
  75. # 设置图片格式
  76. if info['content']['adSite'] != '朋友圈信息流':
  77. self.driver.find_elements_by_xpath('//*[@class="adui-radio-indicator"]')[1].click()
  78. elif info['content']['outerStyle'] != '常规广告':
  79. select_e = self.driver.find_elements_by_xpath('//*[@class="adui-select-selection-item"]')
  80. for _ in select_e:
  81. if _.text == '常规广告':
  82. _.click()
  83. time.sleep(0.1)
  84. select_e = self.driver.find_elements_by_xpath('//*[@class="adui-select-item-option-content"]')
  85. for _ in select_e:
  86. if _.text == '卡片广告':
  87. _.click()
  88. # 上传图片
  89. file_name = re.split('\/', info['content']['url'])[-1]
  90. self.driver.find_element_by_class_name('upload-img-item-inner-2gsg7NjaZ8').click()
  91. WebDriverWait(self.driver, 10).until(
  92. lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if
  93. _.is_displayed() and _.is_enabled()]) > 0)
  94. turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')
  95. can_use_button = []
  96. for _ in turn_page_buttons:
  97. if _.is_enabled() and _.is_displayed():
  98. can_use_button.append(_)
  99. # 不断翻页获取到元素为止
  100. chose_over = False
  101. while True:
  102. page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')
  103. for _ in page_elements:
  104. if _.is_displayed() and _.is_enabled():
  105. if file_name in _.text:
  106. _.click()
  107. chose_over = True
  108. break
  109. if chose_over or len(can_use_button) == 0:
  110. break
  111. # 翻到最后一页时停止
  112. page_text = self.driver.find_element_by_class_name('count_small-37CcvfzoTl').text
  113. page_nums = re.findall('\d+', page_text)
  114. if int(page_nums[0].strip()) == int(page_nums[1].strip()):
  115. break
  116. # 翻页
  117. can_use_button[2].click()
  118. # 确保翻页成功
  119. WebDriverWait(self.driver, 10).until(
  120. lambda x: page_text != self.driver.find_element_by_class_name('count_small-37CcvfzoTl').text)
  121. self.driver.find_element_by_xpath('//*[@id="test_material_container_confirm"]').click()
  122. try:
  123. WebDriverWait(self.driver, 4).until(
  124. lambda driver: driver.find_element_by_class_name(
  125. 'btnFist-uueBS6DQFa'))
  126. _ = self.driver.find_element_by_class_name(
  127. 'btnFist-uueBS6DQFa')
  128. WebDriverWait(self.driver, 4).until(
  129. lambda x: (_.is_displayed() and _.is_enabled()))
  130. time.sleep(1)
  131. _.click()
  132. WebDriverWait(self.driver, 100).until(
  133. lambda driver: driver.find_element_by_class_name(
  134. 'btn-3E823IXt3m'))
  135. _ = self.driver.find_element_by_class_name(
  136. 'btn-3E823IXt3m')
  137. WebDriverWait(self.driver, 100).until(
  138. lambda x: (_.is_displayed() and _.is_enabled()))
  139. time.sleep(1)
  140. _.click()
  141. except Exception as e:
  142. pass
  143. logging.info('头版首页单图上传结束')
  144. def multi_page_set():
  145. # TODO:现在图片设置为素材库,需要对应下载然后存储
  146. self.driver.find_element_by_css_selector(
  147. '#stage-sidebar > div.topArea-qOwEAeNuIn > div > div:nth-child(2)').click()
  148. time.sleep(random.uniform(0.1, 0.2))
  149. page_size = len(info_v)
  150. if page_size == 3:
  151. pass
  152. if page_size == 4:
  153. self.driver.find_element_by_css_selector(
  154. '#stage-settings > div:nth-child(1) > div > div > div:nth-child(3) > div.adui-form-item > div.adui-form-control > div > button:nth-child(2)').click()
  155. if page_size == 6:
  156. self.driver.find_element_by_css_selector(
  157. '#stage-settings > div:nth-child(1) > div > div > div:nth-child(3) > div.adui-form-item > div.adui-form-control > div > button:nth-child(3)').click()
  158. time.sleep(random.uniform(0.1, 0.2))
  159. self.driver.find_element_by_class_name('imageUploadItem-tA9JX0RWua').click()
  160. WebDriverWait(self.driver, 1000).until(
  161. lambda driver: self.driver.find_element_by_class_name('adui-tabs-tab')
  162. )
  163. input_elements = self.driver.find_elements_by_tag_name('input')
  164. input_find_element = None
  165. for _ in input_elements:
  166. if '输入关键词搜索素材' in _.get_attribute('placeholder'):
  167. input_find_element = _
  168. for _ in info_v:
  169. file_name = os.path.basename(_)
  170. logging.info(file_name)
  171. input_find_element.send_keys(file_name)
  172. input_find_element.send_keys(Keys.RETURN)
  173. WebDriverWait(self.driver, 1000).until(
  174. lambda driver: driver.find_element_by_class_name('img-2HvhMmpnzP'))
  175. file_element = self.driver.find_element_by_class_name('img-2HvhMmpnzP')
  176. WebDriverWait(self.driver, 1000).until(
  177. lambda x: (file_element.is_displayed() and file_element.is_enabled()))
  178. ActionChains(self.driver).move_to_element(file_element).perform()
  179. time.sleep(random.uniform(0.5, 1))
  180. file_element.click()
  181. for i in range(len(file_name) + 10):
  182. input_find_element.send_keys(Keys.BACKSPACE)
  183. time.sleep(random.uniform(0.5, 1))
  184. self.driver.find_element_by_xpath('/html/body/div[12]/div/div/div[2]/div/div[3]/button[2]').click()
  185. # 切图操作如果有的话进行对应操作.
  186. for i in range(len(info_v) + 1):
  187. try:
  188. WebDriverWait(self.driver, 6).until(
  189. lambda driver: driver.find_element_by_xpath(
  190. '/html/body/div[13]/div/div/div[2]/div/div[3]/button[2]'))
  191. self.driver.find_element_by_xpath('/html/body/div[13]/div/div/div[2]/div/div[3]/button[2]').click()
  192. except:
  193. pass
  194. logging.info('头版多图选择 结束')
  195. def movie_set():
  196. # TODO:视频转为链接,
  197. file_name = os.path.basename(info_v)
  198. self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/div[1]/div/div[3]/div/div').click()
  199. self.driver.find_element_by_xpath('//*[@class="comptEditButton-2JsnAFdOGZ"]').click()
  200. WebDriverWait(self.driver, 100).until(
  201. lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if
  202. _.is_displayed() and _.is_enabled()]) > 0)
  203. #
  204. turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')
  205. can_use_button = []
  206. for _ in turn_page_buttons:
  207. if _.is_enabled() and _.is_displayed():
  208. can_use_button.append(_)
  209. # 不断翻页获取到元素为止
  210. chose_over = False
  211. while True:
  212. page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')
  213. for _ in page_elements:
  214. if _.is_displayed() and _.is_enabled():
  215. if file_name in _.text:
  216. _.click()
  217. chose_over = True
  218. break
  219. if chose_over or len(can_use_button) == 0:
  220. # can_use_button 数量说明是否可以翻页,如果不可以翻页,则直接停止
  221. break
  222. # 翻到最后一页时停止
  223. page_text_elements = self.driver.find_elements_by_class_name('count_small-37CcvfzoTl')
  224. for _ in page_text_elements:
  225. if _.is_enabled() and _.is_displayed():
  226. page_text = _.text
  227. page_text_element = _
  228. page_nums = re.findall('\d+', page_text)
  229. if int(page_nums[0].strip()) == int(page_nums[1].strip()):
  230. break
  231. # 翻页
  232. can_use_button[2].click()
  233. # 确保翻页成功
  234. WebDriverWait(self.driver, 10).until(
  235. lambda x: page_text != page_text_element.text)
  236. sc_buttons = self.driver.find_elements_by_id('test_material_container_confirm')
  237. for _ in sc_buttons:
  238. if _.is_enabled() and _.is_displayed():
  239. _.click()
  240. info_type = info['type']
  241. info_v = None # TODO: 暂时存在,之后修改好multi_page_set 和movie_set.就删除
  242. if info['type'] == 'topImg':
  243. single_page_set()
  244. if info['type'] == 'topSlider':
  245. multi_page_set()
  246. if info['type'] == 'topVideo':
  247. movie_set()
  248. # 设置头部组件
  249. pass
  250. def set_page(self, config_info):
  251. logging.info('开始设置图片模块')
  252. page_link = config_info['url']
  253. # 设置图片模块
  254. self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[2]/div[1]/div/div').click()
  255. time.sleep(random.uniform(0.1, 0.2))
  256. file_name = re.split('\/', page_link)[-1]
  257. upload_elements = self.driver.find_elements_by_class_name('upload-img-item-inner-2gsg7NjaZ8')
  258. for _ in upload_elements:
  259. if _.is_displayed() and _.is_enabled():
  260. _.click()
  261. WebDriverWait(self.driver, 10).until(
  262. lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if
  263. _.is_displayed() and _.is_enabled()]) > 0)
  264. # 不断翻页获取到元素为止
  265. chose_over = False
  266. logging.info('翻页开始')
  267. while True:
  268. page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')
  269. for _ in page_elements:
  270. if _.is_displayed() and _.is_enabled():
  271. if file_name in _.text:
  272. _.click()
  273. chose_over = True
  274. break
  275. turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')
  276. can_use_button = []
  277. for _ in turn_page_buttons:
  278. if _.is_enabled() and _.is_displayed():
  279. can_use_button.append(_)
  280. if chose_over or len(can_use_button) == 0:
  281. # can_use_button 数量说明是否可以翻页,如果不可以翻页,则直接停止
  282. break
  283. # 翻到最后一页时停止
  284. page_text_elements = self.driver.find_elements_by_class_name('count_small-37CcvfzoTl')
  285. for _ in page_text_elements:
  286. if _.is_enabled() and _.is_displayed():
  287. page_text = _.text
  288. page_text_element = _
  289. page_nums = re.findall('\d+', page_text)
  290. if int(page_nums[0].strip()) == int(page_nums[1].strip()):
  291. break
  292. # 翻页
  293. can_use_button[2].click()
  294. # 确保翻页成功
  295. WebDriverWait(self.driver, 10).until(
  296. lambda x: page_text != page_text_element.text)
  297. logging.info('翻页结束')
  298. sc_buttons = self.driver.find_elements_by_id('test_material_container_confirm')
  299. for _ in sc_buttons:
  300. if _.is_enabled() and _.is_displayed():
  301. _.click()
  302. logging.info('是否截图开始')
  303. try:
  304. WebDriverWait(self.driver, 4).until(
  305. lambda driver: driver.find_element_by_class_name(
  306. 'btnFist-uueBS6DQFa'))
  307. _ = self.driver.find_element_by_class_name(
  308. 'btnFist-uueBS6DQFa')
  309. WebDriverWait(self.driver, 4).until(
  310. lambda x: (_.is_displayed() and _.is_enabled()))
  311. # 已经出现但任需要等待
  312. time.sleep(1)
  313. _.click()
  314. WebDriverWait(self.driver, 100).until(
  315. lambda x: len([_ for _ in self.driver.find_elements_by_class_name('btn-3E823IXt3m') if
  316. _.is_displayed() and _.is_enabled()]) > 0)
  317. for _ in self.driver.find_elements_by_class_name('btn-3E823IXt3m'):
  318. if _.is_displayed() and _.is_enabled():
  319. _.click()
  320. except Exception as e:
  321. logging.info(e)
  322. logging.info('是否截图结束')
  323. # 设置文本边距
  324. if config_info['marginTop'] != 0 or config_info['marginBottom'] != 0:
  325. distance_buttons = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  326. distance_buttons_can_use = []
  327. for _ in distance_buttons:
  328. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '0':
  329. distance_buttons_can_use.append(_)
  330. distance_buttons_can_use[0].click()
  331. for i in range(4):
  332. distance_buttons_can_use[0].send_keys(Keys.BACKSPACE)
  333. distance_buttons_can_use[0].send_keys(config_info['marginTop'])
  334. distance_buttons_can_use[1].click()
  335. for i in range(4):
  336. distance_buttons_can_use[1].send_keys(Keys.BACKSPACE)
  337. distance_buttons_can_use[1].send_keys(config_info['marginBottom'])
  338. logging.info('图片模块设置结束')
  339. def set_content(self, config_info):
  340. logging.info(' 开始设置文本模块')
  341. # 设置文本模块
  342. # 1.文本内容2.文本颜色3.是否加粗4.文本位置设置5.文本大小
  343. # 设置文本内容
  344. self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[2]/div[5]/div/div').click()
  345. time.sleep(random.uniform(0.2, 0.3))
  346. input_elements = self.driver.find_elements_by_xpath('//textarea[@class="adui-input-base"]')
  347. # pyperclip.copy(config_info['text'])
  348. js_base = '''
  349. function copyToClipboard(text) {
  350. var dummy = document.createElement("textarea");
  351. // to avoid breaking orgain page when copying more words
  352. // cant copy when adding below this code
  353. // dummy.style.display = 'none'
  354. document.body.appendChild(dummy);
  355. //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
  356. dummy.value = text;
  357. dummy.select();
  358. document.execCommand("copy");
  359. document.body.removeChild(dummy);
  360. }
  361. '''
  362. content_change = config_info['text']
  363. content_change = content_change.replace("\\", "\\\\")
  364. content_change = content_change.replace('\n', '\\n')
  365. content_change = content_change.replace('\n', '\\n')
  366. content_change = content_change.replace("'", "\'")
  367. js_base = js_base + '''copyToClipboard('{}');'''.format(content_change)
  368. self.driver.execute_script(js_base)
  369. for _ in input_elements:
  370. if _.is_enabled() and _.is_displayed():
  371. _.send_keys(Keys.CONTROL, 'v')
  372. # 设置颜色
  373. if config_info['color'] != '#595959':
  374. color_buttons = self.driver.find_elements_by_class_name('adui-cp-picker')
  375. c_buttons_can_use = []
  376. for _ in color_buttons:
  377. if _.is_displayed() and _.is_enabled():
  378. c_buttons_can_use.append(_)
  379. c_buttons_can_use[1].click()
  380. time.sleep(random.uniform(0.2, 0.3))
  381. input_elements = self.driver.find_elements_by_tag_name('input')
  382. for _ in input_elements:
  383. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '595959':
  384. _.click()
  385. _.send_keys(config_info['color'])
  386. # 设置是否加粗
  387. if config_info['fontWeight'] != 'normal':
  388. big_elements = self.driver.find_elements_by_class_name('adui-button-content')
  389. for _ in big_elements:
  390. if _.text == '加粗' and _.is_displayed() and _.is_enabled():
  391. _.click()
  392. # 设置文本位置
  393. if config_info['textAlign'] != 'left':
  394. loc_buttons = self.driver.find_elements_by_xpath(
  395. "//div[contains(@class, 'adui-button-group_banner')]//button")
  396. loc_buttons_can_use = []
  397. for _ in loc_buttons:
  398. if _.is_enabled() and _.is_displayed():
  399. loc_buttons_can_use.append(_)
  400. if config_info['textAlign'] == 'center':
  401. loc_buttons_can_use[1].click()
  402. if config_info['textAlign'] == 'right':
  403. loc_buttons_can_use[2].click()
  404. # 设置文本大小
  405. if config_info['fontSize'] != 15:
  406. str_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-selection-search']")
  407. str_buttons_can_use = []
  408. for _ in str_buttons:
  409. if _.is_displayed() and _.is_enabled():
  410. str_buttons_can_use.append(_)
  411. str_buttons_can_use[1].click()
  412. time.sleep(random.uniform(0.5, 1))
  413. str_num_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-item-option-content']")
  414. str_num_can_use = []
  415. for _ in str_num_buttons:
  416. if _.is_displayed() and _.is_enabled():
  417. str_num_can_use.append(_)
  418. # str_num_map = {14: 0, 15: 1, 16: 2, 18: 3, 20: 4, 24: 5, 36: 6}
  419. # str_num_can_use[str_num_map[config_info['fontSize']]].click()
  420. for _ in str_num_can_use:
  421. if _.text == str(config_info['fontSize']):
  422. _.click()
  423. # 设置文本边距
  424. if config_info['marginTop'] != 22 or config_info['marginBottom'] != 22:
  425. distance_buttons = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  426. distance_buttons_can_use = []
  427. for _ in distance_buttons:
  428. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '22':
  429. distance_buttons_can_use.append(_)
  430. distance_buttons_can_use[0].click()
  431. for i in range(4):
  432. distance_buttons_can_use[0].send_keys(Keys.BACKSPACE)
  433. distance_buttons_can_use[0].send_keys(config_info['marginTop'])
  434. distance_buttons_can_use[1].click()
  435. for i in range(4):
  436. distance_buttons_can_use[1].send_keys(Keys.BACKSPACE)
  437. distance_buttons_can_use[1].send_keys(config_info['marginBottom'])
  438. def set_follow_button(self, config_info):
  439. # TODO:是否一键关注
  440. # 设置关注按钮
  441. # 0.是否一键关注 1.设置button文本内容 2.是否加粗 3.设置字体颜色,边框颜色,填充色 4.设置边距
  442. self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[4]/div[2]/div/div').click()
  443. # 开始设置一键关注
  444. if 'follow' in config_info.keys():
  445. if not config_info['follow']:
  446. time.sleep(0.1)
  447. follow_bs = self.driver.find_elements_by_xpath(
  448. '//*[@class="form-caption-3Xp3o6Drwf"]/div/span')
  449. for _ in follow_bs:
  450. if _.is_displayed() and _.is_enabled():
  451. _.click()
  452. # 文本设置
  453. input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  454. for _ in input_elements:
  455. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '关注公众号':
  456. _.click()
  457. _.clear()
  458. for i in range(10):
  459. _.send_keys(Keys.BACKSPACE)
  460. _.send_keys(config_info['text'])
  461. # 文本是否加粗
  462. if config_info['fontWeight'] != 'normal':
  463. big_elements = self.driver.find_elements_by_xpath('//span[@class="adui-button-content"]')
  464. for _ in big_elements:
  465. if _.text == '加粗' and _.is_displayed() and _.is_enabled():
  466. _.click()
  467. # 颜色设置
  468. input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  469. input_elements_can_use = []
  470. for _ in input_elements:
  471. if _.is_enabled() and _.is_displayed() and (
  472. _.get_attribute("value") == '07C160' or _.get_attribute("value") == 'FFFFFF'):
  473. input_elements_can_use.append(_)
  474. if config_info['textColor'] != '#FFFFFF':
  475. input_elements_can_use[0].click()
  476. input_elements_can_use[0].send_keys(config_info['textColor'])
  477. time.sleep(random.uniform(0.1, 0.5))
  478. if config_info['borderColor'] != '#FFFFFF':
  479. input_elements_can_use[1].click()
  480. input_elements_can_use[1].send_keys(config_info['borderColor'])
  481. time.sleep(random.uniform(0.1, 0.5))
  482. input_elements_can_use[2].click()
  483. input_elements_can_use[2].send_keys(config_info['backColor'])
  484. time.sleep(random.uniform(0.1, 0.5))
  485. # 间隙设置
  486. size_buttons = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')
  487. size_buttons_can_use = []
  488. for _ in size_buttons:
  489. if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '28':
  490. size_buttons_can_use.append(_)
  491. size_buttons_can_use[0].click()
  492. for i in range(4):
  493. size_buttons_can_use[0].send_keys(Keys.BACKSPACE)
  494. size_buttons_can_use[0].send_keys(config_info['marginTop'])
  495. size_buttons_can_use[1].click()
  496. for i in range(4):
  497. size_buttons_can_use[1].send_keys(Keys.BACKSPACE)
  498. size_buttons_can_use[1].send_keys(config_info['marginBottom'])
  499. def set_text_button(self):
  500. # 设置图文按钮
  501. pass
  502. def send_file_multi(self, layout, err_num=0):
  503. # 有问题,暂时不使用
  504. # 上传文件,文件上传与整体流程切割开
  505. token = re.findall('token=(\d+)', self.driver.current_url)
  506. url_ = 'https://mp.weixin.qq.com/promotion/frame?t=ad_system/common_frame&t1=material_std/material_library&token={}'.format(
  507. token[0])
  508. js = "window.open('{}')".format(url_)
  509. self.driver.execute_script(js)
  510. time.sleep(random.uniform(1, 2))
  511. self.driver.switch_to.window(self.driver.window_handles[-1])
  512. file_set = set()
  513. for v in layout.values():
  514. if isinstance(v, dict):
  515. if 'multi_page' in v.keys() or 'page' in v.keys() or 'movie' in v.keys():
  516. v_name = list(v.keys())[0]
  517. if isinstance(v[v_name], list):
  518. for _ in v[v_name]:
  519. file_set.add(_)
  520. else:
  521. file_set.add(v[v_name])
  522. file_list = list(file_set)
  523. # print(file_list)
  524. # print('file list size', len(file_list))
  525. send_file_sign = self.send_file_limit_num
  526. for _ in file_list:
  527. # print(_)
  528. self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(_)
  529. time.sleep(100)
  530. while True:
  531. # 失败,失败直接退出重跑
  532. # 正在上传数量,如果是正在上传小于限定数量,就不断输入
  533. # 上传完毕,小于限定数量,不断输入,.....已经上传好了,就关闭
  534. time.sleep(1)
  535. send_reslut_content = self.driver.find_element_by_xpath(
  536. '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/div/strong').text
  537. if '失败' in send_reslut_content:
  538. if err_num < 3:
  539. self.send_file(layout, err_num=err_num + 1)
  540. else:
  541. exit()
  542. if '正在上传' in send_reslut_content:
  543. if send_file_sign < len(file_list):
  544. send_num = re.findall('(\d+)', send_reslut_content)[0]
  545. if int(send_num) < self.send_file_limit_num:
  546. # 还可以继续上传
  547. x = send_file_sign
  548. can_send_sign = send_file_sign + (self.send_file_limit_num - send_num)
  549. y = can_send_sign if can_send_sign < len(file_list) else len(file_list)
  550. for i in range(x, y):
  551. send_file_sign = send_file_sign + 1
  552. self.driver.find_element_by_xpath(
  553. '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_list[i])
  554. else:
  555. pass
  556. if '上传成功' in send_reslut_content:
  557. if send_file_sign < len(file_list):
  558. send_num = re.findall('(\d+)', send_reslut_content)[0]
  559. if int(send_num) < self.send_file_limit_num:
  560. # 还可以继续上传
  561. x = send_file_sign
  562. can_send_sign = send_file_sign + (self.send_file_limit_num - send_num)
  563. y = can_send_sign if can_send_sign < len(file_list) else len(file_list)
  564. for i in range(x, y):
  565. send_file_sign = send_file_sign + 1
  566. self.driver.find_element_by_xpath(
  567. '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_list[i])
  568. else:
  569. break
  570. time.sleep(1000)
  571. self.driver.execute_script('window.close();')
  572. def send_file(self, file_link, err_num=0):
  573. # 下载图片,存储于
  574. if not os.path.exists(self.img_dir):
  575. os.makedirs(self.img_dir)
  576. link_pra = re.split('\/', file_link)
  577. file_path = os.getcwd() + '/' + self.img_dir + '/' + link_pra[-1]
  578. rsp = requests.get(file_link)
  579. with open(file_path, 'wb') as f:
  580. f.write(rsp.content)
  581. # 有问题,暂时不使用
  582. self.driver.execute_script('location.reload();')
  583. self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_path)
  584. def send_file_alone(self, layout):
  585. def get_url(v_info):
  586. if 'url' in v_info.keys():
  587. file_set.add(v_info['url'])
  588. for v in v_info.values():
  589. if isinstance(v, dict):
  590. get_url(v)
  591. if isinstance(v, list):
  592. for _ in v:
  593. if isinstance(_, dict):
  594. get_url(_)
  595. # 上传文件,单线程
  596. # 上传文件,文件上传与整体流程切割开
  597. logging.info('开始传送文件')
  598. WebDriverWait(self.driver, 10).until(
  599. lambda x: len(re.findall('token=(\d+)', self.driver.current_url)))
  600. token = re.findall('token=(\d+)', self.driver.current_url)
  601. url_ = 'https://mp.weixin.qq.com/promotion/frame?t=ad_system/common_frame&t1=material_std/material_library&token={}'.format(
  602. token[0])
  603. js = "window.open('{}')".format(url_)
  604. self.driver.execute_script(js)
  605. time.sleep(random.uniform(1, 2))
  606. self.driver.switch_to.window(self.driver.window_handles[-1])
  607. file_set = set()
  608. # TODO:之后还有multi_page 和 movie
  609. # for v in layout.values():
  610. # if isinstance(v, dict):
  611. # if 'multi_page' in v.keys() or 'page' in v.keys() or 'movie' in v.keys():
  612. # v_name = list(v.keys())[0]
  613. # if isinstance(v[v_name], list):
  614. # for _ in v[v_name]:
  615. # file_set.add(_)
  616. # else:
  617. # file_set.add(v[v_name])
  618. get_url(layout)
  619. for _ in file_set:
  620. self.send_file(_)
  621. err_num = 0
  622. while True:
  623. time.sleep(1)
  624. send_reslut_content = self.driver.find_element_by_xpath(
  625. '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/div/strong').text
  626. if '上传成功' in send_reslut_content:
  627. break
  628. if '失败' in send_reslut_content:
  629. err_num = err_num + 1
  630. self.send_file(_)
  631. if err_num > 3:
  632. raise ValueError("图片上传失败")
  633. self.driver.execute_script('window.close();')
  634. self.driver.switch_to.window(self.driver.window_handles[-1])
  635. logging.info('传送文件,结束')
  636. def set_share_content(self, title_content, des_content):
  637. self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div/section/header/div[2]/button[2]').click()
  638. WebDriverWait(self.driver, 50).until(lambda driver: driver.find_element_by_xpath(
  639. '//*[@id="wxadcontainer"]/div[1]/div/div/div/div[1]/section/section/div[2]/div[1]/div/div/input'))
  640. title_input = self.driver.find_element_by_xpath(
  641. '//*[@id="wxadcontainer"]/div[1]/div/div/div/div[1]/section/section/div[2]/div[1]/div/div/input')
  642. title_input.click()
  643. title_input.send_keys(title_content)
  644. des_input = self.driver.find_element_by_xpath(
  645. '//*[@id="wxadcontainer"]/div[1]/div/div/div/div[1]/section/section/div[2]/div[2]/div/div/input')
  646. des_input.click()
  647. des_input.send_keys(des_content)
  648. self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div/header/div[2]/button').click()
  649. WebDriverWait(self.driver, 10).until(
  650. lambda driver: driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/div/div[3]/button[2]'))
  651. self.driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/div/div[3]/button[2]').click()
  652. time.sleep(1)
  653. @staticmethod
  654. def check_sucess_api(log_ad, layout_name):
  655. # 默认在进入公众号初始页面
  656. logging.info('开始检查落地页是否创建成功')
  657. WebDriverWait(log_ad.driver, 100).until(
  658. lambda driver: True if 'token' in log_ad.driver.current_url else False)
  659. cookie_dict = log_ad.get_cookie(log_ad.driver, login_cookie=False)
  660. token_id = re.findall('token=(\d+)', log_ad.driver.current_url)[0]
  661. requests.session()
  662. layout_url = 'https://mp.weixin.qq.com/promotion/landingpage_manager?action=list_pages&page=1&page_size=10&canvas_name={layout_name}&login_from=&is_grant=0&owner_uid=&token={wechat_token}&appid=&spid=&_={time_}'.format(
  663. layout_name=layout_name, wechat_token=token_id, time_=int(time.time() * 1000))
  664. session = requests.session()
  665. rsp = session.get(url=layout_url, cookies=cookie_dict)
  666. result_json = rsp.json()
  667. if 'landing_page_list' in result_json.keys():
  668. if len(result_json['landing_page_list']):
  669. logging.info('对应落地页存在于微信后台')
  670. return True
  671. def remove_all_file(self):
  672. shutil.rmtree(os.getcwd() + '/' + self.img_dir)
  673. pass
  674. def create_layout(self, layout, sql_session, err_num=0):
  675. #
  676. try:
  677. self.send_file_alone(layout)
  678. self.set_advertisement_sign(layout_name=layout['layoutName'])
  679. self.set_head_assemb(layout['topContent'])
  680. self.set_background_color(layout['pageBackColor'])
  681. for _ in layout['content']:
  682. if _['type'] == 'img':
  683. self.set_page(_['content'])
  684. if _['type'] == 'txt':
  685. self.set_content(_['content'])
  686. if _['type'] == 'followAcc':
  687. self.set_follow_button(_['content'])
  688. self.set_share_content(title_content=layout['shareTittle'], des_content=layout['shareDesc'])
  689. self.remove_all_file()
  690. if self.check_sucess_api(layout_name=layout['layoutName'], log_ad=self.log_ad):
  691. return {'sucess': True, 'result_info': ''}
  692. else:
  693. if err_num > 3:
  694. return {'sucess': False, 'result_info': '过程中全程无错误,失败'}
  695. else:
  696. self.log_ad.refresh_driver()
  697. self.log_ad.select_ad_master(service_name=self.service_name, wechat_name=self.wechat_name,
  698. sql_session=sql_session)
  699. self.get_into_create_page()
  700. return self.create_layout(layout, sql_session, err_num=err_num + 1)
  701. except Exception as e:
  702. logging.error(e)
  703. # TODO:有空时讲 e 内容设置为原始内容
  704. if err_num > 3:
  705. return {'sucess': False, 'result_info': str(e)}
  706. else:
  707. self.log_ad.refresh_driver()
  708. self.log_ad.select_ad_master(service_name=self.service_name, wechat_name=self.wechat_name,
  709. sql_session=sql_session)
  710. self.get_into_create_page()
  711. return self.create_layout(layout, sql_session, err_num=err_num + 1)
  712. if __name__ == '__main__':
  713. logging.basicConfig(
  714. handlers=[
  715. logging.handlers.RotatingFileHandler('./create_ad_layout.log',
  716. maxBytes=10 * 1024 * 1024,
  717. backupCount=5,
  718. encoding='utf-8')
  719. , logging.StreamHandler() # 供输出使用
  720. ],
  721. level=logging.INFO,
  722. format="%(asctime)s - %(levelname)s %(filename)s %(funcName)s %(lineno)s - %(message)s"
  723. )