| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679 | from wechat_action.login_ad import LogInfrom selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver import ChromeOptionsfrom selenium.webdriver.common.keys import Keysimport loggingimport timeimport randomimport reimport osfrom logging import handlersclass CreateAd:    def __init__(self):        # TODO:创建完页面需要关闭所有页面并回到一开始的页面        self.driver = LogIn().get_driver_loged()        self.get_into_create_page()        self.send_file_limit_num = 8    def get_into_create_page(self):        # 进入创建页面        self.driver.find_element_by_id('material').click()        WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element_by_class_name('ui-fl-r'))        time.sleep(random.uniform(0.1, 0.2))        self.driver.find_element_by_class_name('ui-fl-r').click()        WebDriverWait(self.driver, 5).until(lambda driver: driver.find_element_by_css_selector(            '#wxadcontainer > div:nth-child(1) > div:nth-child(2) > div.dialog-1fj_N480ZT > div > div > div:nth-child(1) > div.dialogCardFooter-17KpBD1lgN > button'))        self.driver.find_element_by_css_selector(            '#wxadcontainer > div:nth-child(1) > div:nth-child(2) > div.dialog-1fj_N480ZT > div > div > div:nth-child(1) > div.dialogCardFooter-17KpBD1lgN > button').click()        self.driver.switch_to.window(self.driver.window_handles[-1])        WebDriverWait(self.driver, 100).until(lambda driver: driver.find_element_by_class_name('addContent-8pexaaAGYy'))        self.driver.find_element_by_class_name('addContent-8pexaaAGYy').click()        WebDriverWait(self.driver, 100).until(lambda driver: driver.find_element_by_class_name('topArea-qOwEAeNuIn'))    def create_layout(self):        # 数据库获取数据,然后进行编排        # 创建编排        pass    def set_background_color(self):        color_buttons = self.driver.find_elements_by_class_name('adui-cp-picker')        c_buttons_can_use = []        for _ in color_buttons:            if _.is_displayed() and _.is_enabled():                c_buttons_can_use.append(_)        c_buttons_can_use[0].click()        time.sleep(random.uniform(0.2, 0.3))        input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')        for _ in input_elements:            if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == 'FFFFFF':                _.click()                _.send_keys('F7F7F7')    def set_head_assemb(self, info):        def single_page_set():            self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/div[1]/div/div[1]/div/div').click()            time.sleep(random.uniform(0.1, 0.2))            file_name = os.path.basename(info_v)            self.driver.find_element_by_class_name('upload-img-item-inner-2gsg7NjaZ8').click()            WebDriverWait(self.driver, 10).until(                lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if                               _.is_displayed() and _.is_enabled()]) > 0)            turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')            can_use_button = []            for _ in turn_page_buttons:                if _.is_enabled() and _.is_displayed():                    can_use_button.append(_)            # 不断翻页获取到元素为止            chose_over = False            while True:                page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')                for _ in page_elements:                    if _.is_displayed() and _.is_enabled():                        if file_name in _.text:                            _.click()                            chose_over = True                            break                if chose_over or len(can_use_button) == 0:                    break                # 翻到最后一页时停止                page_text = self.driver.find_element_by_class_name('count_small-37CcvfzoTl').text                page_nums = re.findall('\d+', page_text)                if int(page_nums[0].strip()) == int(page_nums[1].strip()):                    break                # 翻页                can_use_button[2].click()                # 确保翻页成功                WebDriverWait(self.driver, 10).until(                    lambda x: page_text != self.driver.find_element_by_class_name('count_small-37CcvfzoTl').text)            self.driver.find_element_by_xpath('//*[@id="test_material_container_confirm"]').click()            try:                WebDriverWait(self.driver, 4).until(                    lambda driver: driver.find_element_by_class_name(                        'btnFist-uueBS6DQFa'))                _ = self.driver.find_element_by_class_name(                    'btnFist-uueBS6DQFa')                WebDriverWait(self.driver, 4).until(                    lambda x: (_.is_displayed() and _.is_enabled()))                time.sleep(1)                _.click()                WebDriverWait(self.driver, 100).until(                    lambda driver: driver.find_element_by_class_name(                        'btn-3E823IXt3m'))                _ = self.driver.find_element_by_class_name(                    'btn-3E823IXt3m')                WebDriverWait(self.driver, 100).until(                    lambda x: (_.is_displayed() and _.is_enabled()))                time.sleep(1)                _.click()            except Exception as e:                pass            logging.info('头版首页单图上传结束')        def multi_page_set():            self.driver.find_element_by_css_selector(                '#stage-sidebar > div.topArea-qOwEAeNuIn > div > div:nth-child(2)').click()            time.sleep(random.uniform(0.1, 0.2))            page_size = len(info_v)            if page_size == 3:                pass            if page_size == 4:                self.driver.find_element_by_css_selector(                    '#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()            if page_size == 6:                self.driver.find_element_by_css_selector(                    '#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()            time.sleep(random.uniform(0.1, 0.2))            self.driver.find_element_by_class_name('imageUploadItem-tA9JX0RWua').click()            WebDriverWait(self.driver, 1000).until(                lambda driver: self.driver.find_element_by_class_name('adui-tabs-tab')            )            input_elements = self.driver.find_elements_by_tag_name('input')            input_find_element = None            for _ in input_elements:                if '输入关键词搜索素材' in _.get_attribute('placeholder'):                    input_find_element = _            for _ in info_v:                file_name = os.path.basename(_)                logging.info(file_name)                input_find_element.send_keys(file_name)                input_find_element.send_keys(Keys.RETURN)                WebDriverWait(self.driver, 1000).until(                    lambda driver: driver.find_element_by_class_name('img-2HvhMmpnzP'))                file_element = self.driver.find_element_by_class_name('img-2HvhMmpnzP')                WebDriverWait(self.driver, 1000).until(                    lambda x: (file_element.is_displayed() and file_element.is_enabled()))                ActionChains(self.driver).move_to_element(file_element).perform()                time.sleep(random.uniform(1, 2))                file_element.click()                for i in range(len(file_name) + 10):                    input_find_element.send_keys(Keys.BACKSPACE)                time.sleep(random.uniform(1, 4))            self.driver.find_element_by_xpath('/html/body/div[12]/div/div/div[2]/div/div[3]/button[2]').click()            time.sleep(random.uniform(2, 4))            # 切图操作如果有的话进行对应操作.            for i in range(len(info_v) + 1):                try:                    WebDriverWait(self.driver, 4).until(                        lambda driver: driver.find_element_by_xpath(                            '/html/body/div[13]/div/div/div[2]/div/div[3]/button[2]'))                    self.driver.find_element_by_xpath('/html/body/div[13]/div/div/div[2]/div/div[3]/button[2]').click()                except:                    pass            logging.info('头版多图选择 结束')        def movie_set():            file_name = os.path.basename(info_v)            self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/div[1]/div/div[3]/div/div').click()            self.driver.find_element_by_xpath('//*[@class="comptEditButton-2JsnAFdOGZ"]').click()            WebDriverWait(self.driver, 100).until(                lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if                               _.is_displayed() and _.is_enabled()]) > 0)            #            turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')            can_use_button = []            for _ in turn_page_buttons:                if _.is_enabled() and _.is_displayed():                    can_use_button.append(_)            # 不断翻页获取到元素为止            chose_over = False            while True:                page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')                for _ in page_elements:                    if _.is_displayed() and _.is_enabled():                        if file_name in _.text:                            _.click()                            chose_over = True                            break                if chose_over or len(can_use_button) == 0:                    # can_use_button 数量说明是否可以翻页,如果不可以翻页,则直接停止                    break                # 翻到最后一页时停止                page_text_elements = self.driver.find_elements_by_class_name('count_small-37CcvfzoTl')                for _ in page_text_elements:                    if _.is_enabled() and _.is_displayed():                        page_text = _.text                        page_text_element = _                page_nums = re.findall('\d+', page_text)                if int(page_nums[0].strip()) == int(page_nums[1].strip()):                    break                # 翻页                can_use_button[2].click()                # 确保翻页成功                WebDriverWait(self.driver, 10).until(                    lambda x: page_text != page_text_element.text)            sc_buttons = self.driver.find_elements_by_id('test_material_container_confirm')            for _ in sc_buttons:                if _.is_enabled() and _.is_displayed():                    _.click()        info_key = list(info.keys())[0]        info_v = info[info_key]        if info_key == 'page':            single_page_set()        if info_key == 'multi_page':            multi_page_set()        if info_key == 'movie':            movie_set()        # 设置头部组件        pass    def set_page(self, page_path):        # 设置图片模块        self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[2]/div[1]/div/div').click()        time.sleep(random.uniform(0.1, 0.2))        file_name = os.path.basename(page_path)        upload_elements = self.driver.find_elements_by_class_name('upload-img-item-inner-2gsg7NjaZ8')        for _ in upload_elements:            if _.is_displayed() and _.is_enabled():                _.click()        WebDriverWait(self.driver, 10).until(            lambda x: len([_ for _ in self.driver.find_elements_by_class_name('title-29sncpKgTl') if                           _.is_displayed() and _.is_enabled()]) > 0)        turn_page_buttons = self.driver.find_elements_by_class_name('paginationIcon-1EfoH0sNRF')        can_use_button = []        for _ in turn_page_buttons:            if _.is_enabled() and _.is_displayed():                can_use_button.append(_)        # 不断翻页获取到元素为止        chose_over = False        while True:            page_elements = self.driver.find_elements_by_class_name('title-29sncpKgTl')            for _ in page_elements:                if _.is_displayed() and _.is_enabled():                    if file_name in _.text:                        _.click()                        chose_over = True                        break            if chose_over or len(can_use_button) == 0:                # can_use_button 数量说明是否可以翻页,如果不可以翻页,则直接停止                break            # 翻到最后一页时停止            page_text_elements = self.driver.find_elements_by_class_name('count_small-37CcvfzoTl')            for _ in page_text_elements:                if _.is_enabled() and _.is_displayed():                    page_text = _.text                    page_text_element = _            page_nums = re.findall('\d+', page_text)            if int(page_nums[0].strip()) == int(page_nums[1].strip()):                break            # 翻页            can_use_button[2].click()            # 确保翻页成功            WebDriverWait(self.driver, 10).until(                lambda x: page_text != page_text_element.text)        sc_buttons = self.driver.find_elements_by_id('test_material_container_confirm')        for _ in sc_buttons:            if _.is_enabled() and _.is_displayed():                _.click()        try:            WebDriverWait(self.driver, 4).until(                lambda driver: driver.find_element_by_class_name(                    'btnFist-uueBS6DQFa'))            _ = self.driver.find_element_by_class_name(                'btnFist-uueBS6DQFa')            WebDriverWait(self.driver, 4).until(                lambda x: (_.is_displayed() and _.is_enabled()))            # 已经出现但任需要等待            time.sleep(1)            _.click()            WebDriverWait(self.driver, 100).until(                lambda x: len([_ for _ in self.driver.find_elements_by_class_name('btn-3E823IXt3m') if                               _.is_displayed() and _.is_enabled()]) > 0)            for _ in self.driver.find_elements_by_class_name('btn-3E823IXt3m'):                if _.is_displayed() and _.is_enabled():                    _.click()        except Exception as e:            logging.info(e)        logging.info('图片模块设置结束')    def set_title(self, title_content):        # 设置标题模块        self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[2]/div[5]/div/div').click()        time.sleep(random.uniform(0.2, 0.3))        input_elements = self.driver.find_elements_by_xpath('//textarea[@class="adui-input-base"]')        for _ in input_elements:            if _.is_enabled() and _.is_displayed():                _.send_keys(title_content)        color_buttons = self.driver.find_elements_by_class_name('adui-cp-picker')        c_buttons_can_use = []        for _ in color_buttons:            if _.is_displayed() and _.is_enabled():                c_buttons_can_use.append(_)        c_buttons_can_use[1].click()        time.sleep(random.uniform(0.2, 0.3))        input_elements = self.driver.find_elements_by_tag_name('input')        for _ in input_elements:            if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '595959':                _.click()                _.send_keys('DE2821')        big_elements = self.driver.find_elements_by_class_name('adui-button-content')        for _ in big_elements:            if _.text == '加粗' and _.is_displayed() and _.is_enabled():                _.click()        loc_buttons = self.driver.find_elements_by_xpath("//div[contains(@class, 'adui-button-group_banner')]//button")        loc_buttons_can_use = []        for _ in loc_buttons:            if _.is_enabled() and _.is_displayed():                loc_buttons_can_use.append(_)        loc_buttons_can_use[1].click()        str_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-selection__rendered']")        str_buttons_can_use = []        for _ in str_buttons:            if _.is_displayed() and _.is_enabled():                str_buttons_can_use.append(_)        str_buttons_can_use[1].click()        time.sleep(random.uniform(1, 3))        str_num_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-dropdown-menu-item']")        str_num_can_use = []        for _ in str_num_buttons:            if _.is_displayed() and _.is_enabled():                str_num_can_use.append(_)        str_num_can_use[4].click()    def set_content(self, content_content):        # 输入文本内容        self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[2]/div[5]/div/div').click()        time.sleep(random.uniform(0.2, 0.3))        input_elements = self.driver.find_elements_by_xpath('//textarea[@class="adui-input-base"]')        for _ in input_elements:            if _.is_enabled() and _.is_displayed():                _.send_keys(content_content)        str_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-selection__rendered']")        str_buttons_can_use = []        for _ in str_buttons:            if _.is_displayed() and _.is_enabled():                str_buttons_can_use.append(_)        str_buttons_can_use[1].click()        time.sleep(random.uniform(1, 3))        str_num_buttons = self.driver.find_elements_by_xpath("//*[@class='adui-select-dropdown-menu-item']")        str_num_can_use = []        for _ in str_num_buttons:            if _.is_displayed() and _.is_enabled():                str_num_can_use.append(_)        str_num_can_use[3].click()    def set_follow_button(self, button_type):        # 设置关注按钮        self.driver.find_element_by_xpath('//*[@id="stage-sidebar"]/section/div[4]/div[2]/div/div').click()        if button_type == 1:            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '关注公众号':                    _.click()                    _.clear()                    for i in range(10):                        _.send_keys(Keys.BACKSPACE)                    _.send_keys('保存阅读记录')            big_elements = self.driver.find_elements_by_xpath('//span[@class="adui-button-content"]')            for _ in big_elements:                if _.text == '加粗' and _.is_displayed() and _.is_enabled():                    _.click()            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '07C160':                    _.click()                    _.send_keys('DE2821')        if button_type == 2:            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '关注公众号':                    _.click()                    _.clear()                    for i in range(10):                        _.send_keys(Keys.BACKSPACE)                    _.send_keys('点击此处,继续阅读')            big_elements = self.driver.find_elements_by_xpath('//span[@class="adui-button-content"]')            for _ in big_elements:                if _.text == '加粗' and _.is_displayed() and _.is_enabled():                    _.click()            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '07C160':                    _.click()                    _.send_keys('DE2821')            size_buttons = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            size_buttons_can_use = []            for _ in size_buttons:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '28':                    size_buttons_can_use.append(_)            size_buttons_can_use[0].click()            for i in range(4):                size_buttons_can_use[0].send_keys(Keys.BACKSPACE)            size_buttons_can_use[0].send_keys('0')            size_buttons_can_use[1].click()            for i in range(4):                size_buttons_can_use[1].send_keys(Keys.BACKSPACE)            size_buttons_can_use[1].send_keys('0')        if button_type == 3:            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '关注公众号':                    _.click()                    _.clear()                    for i in range(10):                        _.send_keys(Keys.BACKSPACE)                    _.send_keys('点我,继续阅读')            big_elements = self.driver.find_elements_by_xpath('//span[@class="adui-button-content"]')            for _ in big_elements:                if _.text == '加粗' and _.is_displayed() and _.is_enabled():                    _.click()            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '07C160':                    _.click()                    _.send_keys('FFFFFF')            input_elements = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            for _ in input_elements:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == 'FFFFFF':                    _.click()                    _.send_keys('DE2821')                    break            size_buttons = self.driver.find_elements_by_xpath('//input[@class="adui-input-base"]')            size_buttons_can_use = []            for _ in size_buttons:                if _.is_enabled() and _.is_displayed() and _.get_attribute("value") == '28':                    size_buttons_can_use.append(_)            size_buttons_can_use[0].click()            for i in range(4):                size_buttons_can_use[0].send_keys(Keys.BACKSPACE)            size_buttons_can_use[0].send_keys('0')            size_buttons_can_use[1].click()            for i in range(4):                size_buttons_can_use[1].send_keys(Keys.BACKSPACE)            size_buttons_can_use[1].send_keys('100')    def set_movie(self):        # 设置视频        pass    def set_text_button(self):        # 设置图文按钮        pass    def send_file_multi(self, layout, err_num=0):        # 有问题,暂时不使用        # 上传文件,文件上传与整体流程切割开        token = re.findall('token=(\d+)', self.driver.current_url)        url_ = 'https://mp.weixin.qq.com/promotion/frame?t=ad_system/common_frame&t1=material_std/material_library&token={}'.format(            token[0])        js = "window.open('{}')".format(url_)        self.driver.execute_script(js)        time.sleep(random.uniform(1, 2))        self.driver.switch_to.window(self.driver.window_handles[-1])        file_set = set()        for v in layout.values():            if isinstance(v, dict):                if 'multi_page' in v.keys() or 'page' in v.keys() or 'movie' in v.keys():                    v_name = list(v.keys())[0]                    if isinstance(v[v_name], list):                        for _ in v[v_name]:                            file_set.add(_)                    else:                        file_set.add(v[v_name])        file_list = list(file_set)        # print(file_list)        # print('file list size', len(file_list))        send_file_sign = self.send_file_limit_num        for _ in file_list:            # print(_)            self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(_)        time.sleep(100)        while True:            # 失败,失败直接退出重跑            # 正在上传数量,如果是正在上传小于限定数量,就不断输入            # 上传完毕,小于限定数量,不断输入,.....已经上传好了,就关闭            time.sleep(1)            send_reslut_content = self.driver.find_element_by_xpath(                '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/div/strong').text            if '失败' in send_reslut_content:                if err_num < 3:                    self.send_file(layout, err_num=err_num + 1)                else:                    exit()            if '正在上传' in send_reslut_content:                if send_file_sign < len(file_list):                    send_num = re.findall('(\d+)', send_reslut_content)[0]                    if int(send_num) < self.send_file_limit_num:                        # 还可以继续上传                        x = send_file_sign                        can_send_sign = send_file_sign + (self.send_file_limit_num - send_num)                        y = can_send_sign if can_send_sign < len(file_list) else len(file_list)                        for i in range(x, y):                            send_file_sign = send_file_sign + 1                            self.driver.find_element_by_xpath(                                '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_list[i])                else:                    pass            if '上传成功' in send_reslut_content:                if send_file_sign < len(file_list):                    send_num = re.findall('(\d+)', send_reslut_content)[0]                    if int(send_num) < self.send_file_limit_num:                        # 还可以继续上传                        x = send_file_sign                        can_send_sign = send_file_sign + (self.send_file_limit_num - send_num)                        y = can_send_sign if can_send_sign < len(file_list) else len(file_list)                        for i in range(x, y):                            send_file_sign = send_file_sign + 1                            self.driver.find_element_by_xpath(                                '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_list[i])                else:                    break        time.sleep(1000)        self.driver.execute_script('window.close();')    def send_file(self, file_path, err_num=0):        # 有问题,暂时不使用        self.driver.execute_script('location.reload();')        self.driver.find_element_by_xpath('//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/input').send_keys(file_path)    def send_file_alone(self, layout):        # 上传文件,单线程        # 上传文件,文件上传与整体流程切割开        token = re.findall('token=(\d+)', self.driver.current_url)        url_ = 'https://mp.weixin.qq.com/promotion/frame?t=ad_system/common_frame&t1=material_std/material_library&token={}'.format(            token[0])        js = "window.open('{}')".format(url_)        self.driver.execute_script(js)        time.sleep(random.uniform(1, 2))        self.driver.switch_to.window(self.driver.window_handles[-1])        file_set = set()        for v in layout.values():            if isinstance(v, dict):                if 'multi_page' in v.keys() or 'page' in v.keys() or 'movie' in v.keys():                    v_name = list(v.keys())[0]                    if isinstance(v[v_name], list):                        for _ in v[v_name]:                            file_set.add(_)                    else:                        file_set.add(v[v_name])        for _ in file_set:            self.send_file(_)            err_num = 0            while True:                time.sleep(1)                send_reslut_content = self.driver.find_element_by_xpath(                    '//*[@id="wxadcontainer"]/div[1]/div[2]/div[4]/div/strong').text                if '上传成功' in send_reslut_content:                    break                if '失败' in send_reslut_content:                    err_num = err_num + 1                    self.send_file(_)                    if err_num > 3:                        # TODO:退出机制需要考虑一下,tornado返回错误信息                        exit()        self.driver.execute_script('window.close();')        self.driver.switch_to.window(self.driver.window_handles[-1])    def send_moive_spic(self):        # 特殊情况下,上传本地视频        pass    def get_layout(self):        # TODO:设置重试机制,然后错误后试错几次,查看是否成功        # 得到编排        layout = {-2: {'bc_color': True},                  -1: {'page': '/usr/share/wallpapers/deepin/Beach_by_Samuel_Scrimshaw.jpg'},                  0: {'title': '这是标题'},                  1: {'content': '这是文本'},                  2: {'follow_button': 1},                  3: {'title': '这是标题'},                  4: {'content': '这是文本'},                  5: {'page': '/usr/share/wallpapers/deepin/Beach_by_Samuel_Scrimshaw.jpg'},                  6: {'page': '/usr/share/wallpapers/deepin/Beach_by_Samuel_Scrimshaw.jpg'},                  7: {'follow_button': 2},                  8: {'follow_button': 3},                  }        # TODO:测试,多图,测试,图文表        layout = {-1: {'multi_page': ['/usr/share/wallpapers/deepin/Beach_by_Samuel_Scrimshaw.jpg',                                      '/usr/share/wallpapers/deepin/Sunset_of_the_Lake_Nam_by_Wang_Jinyu.jpg',                                      '/usr/share/wallpapers/deepin/The_Gongga_Mountain_by_wangjinyu.jpg',                                      '/usr/share/wallpapers/deepin/Reflection_of_the_Kanas_Lake_by_Wang_Jinyu.jpg']},                  0: {'page': '/usr/share/wallpapers/deepin/Beach_by_Samuel_Scrimshaw.jpg'}                  }        layout = {            -2: {'bc_color': True},            -1: {'movie': '/home/cxyu/Downloads/老奶奶.mp4'},            0: {'title': '第一章'},            1: {'content': 'asdfasdf'},            2: {'follow_button': 1},            3: {'page': '/usr/share/wallpapers/deepin/Reflection_of_the_Kanas_Lake_by_Wang_Jinyu.jpg'},            4: {'title': '第二章'},            5: {'content': 'asdfadsfasdfasd'},            6: {'follow_button': 2},            7: {'follow_button': 3},        }        # self.send_file_alone(layout)        self.set_head_assemb(layout[-1])        if -2 in layout.keys():            self.set_background_color()        for _ in range(max(layout.keys()) + 1):            info = layout[_]            info_key = list(info.keys())[0]            info_v = info[info_key]            if info_key == 'page':                self.set_page(info_v)            if info_key == 'title':                self.set_title(info_v)            if info_key == 'content':                self.set_content(info_v)            if info_key == 'follow_button':                self.set_follow_button(info_v)        time.sleep(100)if __name__ == '__main__':    logging.basicConfig(        handlers=[            logging.handlers.RotatingFileHandler('./create_ad.log',                                                 maxBytes=10 * 1024 * 1024,                                                 backupCount=5,                                                 encoding='utf-8')            , logging.StreamHandler()  # 供输出使用        ],        level=logging.INFO,        format="%(asctime)s - %(levelname)s %(filename)s %(funcName)s %(lineno)s - %(message)s"    )    create_ad = CreateAd()    create_ad.get_layout()
 |