create_ad_layout.py 37 KB

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