create_ad_layout.py 38 KB

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