Ejemplo n.º 1
0
 def test_logIn(self):
     # Test name: logIn
     # Step # | name | target | value
     # 1 | open | /?fromurl=http%3A%2F%2Fcrm.test.k8s.ustax.com.cn%2F |
     self.driver.get(
         "http://sso.test.k8s.ustax.com.cn/?fromurl=http%3A%2F%2Fcrm.test.k8s.ustax.com.cn%2F"
     )
     # 2 | setWindowSize | 1936x1056 |
     self.driver.set_window_size(1936, 1056)
     # 3 | click | css=.el-form-item:nth-child(1) .el-input__inner |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(1) .el-input__inner").click()
     # 4 | type | css=.el-form-item:nth-child(1) .el-input__inner | 17585571191
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(1) .el-input__inner").send_keys(
             "17585571191")
     # 5 | click | css=.el-form-item:nth-child(2) .el-input__inner |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(2) .el-input__inner").click()
     # 6 | click | css=.el-form-item:nth-child(2) .el-input__inner |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(2) .el-input__inner").click()
     # 7 | type | css=.el-form-item:nth-child(2) .el-input__inner | resicoit999
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(2) .el-input__inner").send_keys(
             "resicoit999")
     # 8 | click | css=.v-button-ok |
     self.driver.find_element(By.CSS_SELECTOR, ".v-button-ok").click()
     # 9 | click | css=.el-submenu:nth-child(3) .v-menu-container_submenu_text |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-submenu:nth-child(3) .v-menu-container_submenu_text").click()
     # 10 | click | css=.el-menu-item:nth-child(2) span |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".el-menu-item:nth-child(2) span").click()
     # 11 | mouseOver | linkText=私有库 |
     element = self.driver.find_element(By.LINK_TEXT, "私有库")
     actions = ActionChains(self.driver)
     actions.move_to_element(element).perform()
     # 12 | click | css=.el-button--primary:nth-child(3) > span |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-button--primary:nth-child(3) > span").click()
     # 13 | click | css=.el-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner"
     ).click()
     # 14 | click | css=.is-error .el-input__inner |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".is-error .el-input__inner").click()
     # 15 | type | css=.is-error .el-input__inner | 私有库新增录制用户二
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".is-error .el-input__inner").send_keys("私有库新增录制用户二")
     # 16 | type | css=.el-input-group > .el-input__inner | 152108293333
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-input-group > .el-input__inner").send_keys("152108293333")
     # 17 | click | css=.is-error .el-input__inner |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".is-error .el-input__inner").click()
     # 18 | type | css=.is-error .el-input__inner | 私有库新增录制用户三
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".is-error .el-input__inner").send_keys("私有库新增录制用户三")
     # 19 | click | css=.is-focus > .el-input__inner |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".is-focus > .el-input__inner").click()
     # 20 | click | css=.hover |
     self.driver.find_element(By.CSS_SELECTOR, ".hover").click()
     # 21 | click | css=.el-cascader .el-input__inner |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".el-cascader .el-input__inner").click()
     # 22 | click | css=#cascader-menu-812-0-2 > .el-cascader-node__label |
     self.driver.find_element(
         By.CSS_SELECTOR,
         "#cascader-menu-812-0-2 > .el-cascader-node__label").click()
     # 23 | click | css=#cascader-menu-8537-1-2 > .el-cascader-node__label |
     self.driver.find_element(
         By.CSS_SELECTOR,
         "#cascader-menu-8537-1-2 > .el-cascader-node__label").click()
     # 24 | click | css=#cascader-menu-1029-2-1 > .el-cascader-node__label |
     self.driver.find_element(
         By.CSS_SELECTOR,
         "#cascader-menu-1029-2-1 > .el-cascader-node__label").click()
     # 25 | click | css=.el-textarea__inner |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".el-textarea__inner").click()
     # 26 | type | css=.el-textarea__inner | 123号
     self.driver.find_element(By.CSS_SELECTOR,
                              ".el-textarea__inner").send_keys("123号")
     # 27 | click | css=.el-form-item:nth-child(8) .el-input__inner |
     self.driver.find_element(
         By.CSS_SELECTOR,
         ".el-form-item:nth-child(8) .el-input__inner").click()
     # 28 | click | css=.hover:nth-child(7) |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".hover:nth-child(7)").click()
     # 29 | click | css=.el-button:nth-child(3) > span |
     self.driver.find_element(By.CSS_SELECTOR,
                              ".el-button:nth-child(3) > span").click()
     # 30 | close |  |
     self.driver.close()
     # 31 | close |  |
     self.driver.close()
Ejemplo n.º 2
0
 def input_verify_code(self, code):
     action_a = ActionChains(self.driver)
     action_a.move_to_element(self.driver.find_element(
         *loc.ipt_verify_code)).click().send_keys(code).perform()  # 输入异常验证码
Ejemplo n.º 3
0
    def parse(self, response):

        self.create_database_table()

        # Settings window size as per github issue-#11637 phantomjs
        self.driver.set_window_size(1024, 768)

        self.driver.get(response.url)

        # Wait for 10 seconds till is loads.
        self.driver.implicitly_wait(10)

        # From airport input
        from_airport = self.driver.find_element_by_name('fromAirportName')

        # Requires click first to trigger adults selection
        from_airport.click()
        from_airport.clear()
        from_airport.send_keys(self.FLIGHT_FROM['AIRPORT_NAME'])

        # To airport input
        # Requires click first to trigger adults selection
        to_airport = self.driver.find_element_by_css_selector(
            'input[name="toAirportIATA"]')
        to_airport.click()
        to_airport.send_keys(self.FLIGHT_TO['AIRPORT_NAME'])

        # Display extra options
        self.driver.execute_script(
            "document.getElementsByClassName('form-options')[0].style.display='block';"
        )
        # From date triggers a click to display dropdown
        from_data = self.driver.find_element_by_class_name(
            'datepicker-flight-from-trigger')

        from_data.click()

        # Gets datepicker element dirty hack as click not always works
        while True:
            try:
                datepicker = self.driver.find_element_by_class_name(
                    'datepicker')
            except:
                from_data = self.driver.find_element_by_class_name(
                    'datepicker-flight-from-trigger')
                from_data.click()
            else:
                break

        # Check the month name
        month_element_from_text = datepicker.find_element_by_css_selector(
            '.datepicker-days .table-condensed .datepicker-switch').text

        while self.FLIGHT_FROM['MONTH'] not in month_element_from_text:
            datepicker.find_element_by_class_name('next').click()
            month_element_from_text = datepicker.find_element_by_css_selector(
                '.datepicker-days .table-condensed .datepicker-switch').text

        # Gets all days in calendar
        days_elements = datepicker.find_elements_by_class_name('day')

        # Loops through and triggers a click
        for day in days_elements:
            if "old" in day.get_attribute('class'):
                continue
            if day.text == self.FLIGHT_FROM['DATE']:
                day.click()
                break

        # To date triggers a click to display dropdown
        self.driver.find_element_by_class_name(
            'datepicker-flight-to-trigger').click()

        self.driver.implicitly_wait(40)

        # Gets datepicker element
        datepicker = self.driver.find_element_by_class_name('datepicker-days')

        # Check the month name
        month_element_to_text = datepicker.find_element_by_css_selector(
            '.datepicker-days .table-condensed .datepicker-switch').text

        while self.FLIGHT_TO['MONTH'] not in month_element_to_text:
            datepicker.find_element_by_class_name('next').click()
            month_element_to_text = datepicker.find_element_by_css_selector(
                '.datepicker-days .table-condensed .datepicker-switch').text

        # Gets all days in calendar
        days_elements = datepicker.find_elements_by_class_name('day')

        # Loops through and triggers a click
        for day in days_elements:
            if "old" in day.get_attribute('class'):
                continue
            if day.text == self.FLIGHT_TO['DATE']:
                day.click()
                break

        adult_elements = (
            self.driver.find_elements_by_class_name('adults-basic-item'))
        # Selecting two Adults
        for element in adult_elements:
            if element.text == str(self.FLIGHT_PERSONS['ADULTS_NO']):
                element.click()

        if self.FLIGHT_PERSONS['KIDS_NO']:
            # Triggers children dropdown
            self.driver.find_element_by_name('CHILD').click()

            # Selecting two childrens
            children_elements = (self.driver.find_elements_by_css_selector(
                '.children .custom-dropdown-item'))

            for element in children_elements:
                if element.text == str(self.FLIGHT_PERSONS['KIDS_NO']):
                    element.click()

        # Submit a form
        submit_button = self.driver.find_element_by_class_name(
            'submit-button-validation')

        actions = ActionChains(self.driver)
        actions.move_to_element(submit_button).click(submit_button).perform()

        self.driver.implicitly_wait(60)

        # Gets total price
        price = self.driver.find_element_by_css_selector(
            '.prc.flr.ng-binding').text

        price = Decimal(price.strip('GBP'))

        self.save_to_database(price)
Ejemplo n.º 4
0
                          chrome_options=chrome_options)
#driver=webdriver.Firefox()

# Переходим на страницу, на которой нужно что-то сделать
driver.get('https://vk.com/')

# Получаем указатель на поле ввода текста в форме постинга
textarea = driver.find_element_by_css_selector('#index_email')
# Печатаем в поле ввода какой-либо текст
textarea.send_keys('*****@*****.**')

# Получаем указатель на поле ввода пароля
textarea = driver.find_element_by_css_selector('#index_pass')
# Печатаем в поле ввода пароль
textarea.send_keys('WrongPassword')

#Получаем указатель на кнопку "Войти"
submit = driver.find_element_by_css_selector('#index_login_button')
submit.click()
#Ждём пока загрузится кнопка "диалоги"
messages_button = ui.WebDriverWait(
    driver, 15).until(lambda driver: driver.find_element_by_id('l_msg'))
#Нажимаем эту кнопку через Ctrl (в новой вкладке)
ActionChains(driver) \
    .key_down(Keys.CONTROL) \
    .click(messages_button) \
    .key_up(Keys.CONTROL) \
    .perform()
#driver.close()
#sleep(10)
Ejemplo n.º 5
0
    def StartBid(self):
        """
        Start bidding.
        :param biddict:
        :return:
        """
        # First, we need to wait for bid cycle start.
        #self.WaitForBidStart()
        self.logger("Round:{} Policy: YFFS, StartBiding...". format(str(self.round)))
        self.logger(str(self.biddict))

        # set sleeping interval
        sleeping = 30
        cur_time = time.strftime('%H:%M:%S')
        if (cur_time >= '10:12:00') and (cur_time < '22:00:00'):
            sleeping = 60

        time.sleep(sleeping)
        for key, value in self.biddict.items():
            if (value[0] < 20) and (value[0] != 0xff) and (value[0] in self.bidreferencetable) and (self.bidreferencetable[value[0]] > 0):
                # Click WuXing
                time.sleep(3)
                wuxing = self.driver.find_element_by_css_selector("a[class='btn b0'][data-bettype='1'][data-subid='12345']")
                self.wait_and_click(wuxing)
                time.sleep(2)
                # Click BuDingWei
                budingwei = self.driver.find_element_by_css_selector("a[class='btn b0'][data-bettype='5'][data-subid='1123']")
                self.wait_and_click(budingwei)
                time.sleep(2)
                # WuXingYiMa BuDingWei
                wuxingyima = self.driver.find_element_by_css_selector("input[name='r0'][type='radio'][class='pointer'][value='2_5_112345']")
                self.wait_and_click(wuxingyima)
                time.sleep(2)
                # Select Bid Number, 5, e.g.
                # driver.find_element_by_css_selector("a[data-num='5'][class='isNum']").click()
                # We should apply actual bid num from biddict:
                bidnum = self.driver.find_element_by_css_selector("a[data-num={0}][class='isNum']".format( \
                    ''.join(["\'", str(key), "\'"])))
                self.wait_and_click(bidnum)
                time.sleep(1)
                # Drag slider bar to leftmost to get most bonus rate
                dragsource = self.driver.find_element_by_css_selector(
                    "span[class='ui-slider-handle ui-state-default ui-corner-all'][tabindex='0']")
                dragtarget = self.driver.find_element_by_css_selector("i[class='fa fa-plus-circle fs18 minus']")
                ActionChains(self.driver).drag_and_drop(dragsource, dragtarget).perform()
                time.sleep(1)
                # Set Bid value according to biddict[key][1]
                self.driver.find_element_by_id('buyamount').clear()
                time.sleep(1)
                self.driver.find_element_by_id('buyamount').send_keys(str(self.bidreferencetable[self.biddict[key][0]]))
                time.sleep(1)
                # Select bid unit
                # value = 1 : yuan
                # value = 10 : jiao
                # value = 100 : fen
                select = Select(self.driver.find_element_by_id("selectdollarunit"))
                select.select_by_value(str(self.bidunit))
                time.sleep(1)
                # Add to bid list
                addlist = self.driver.find_element_by_css_selector("a[class='btn2'][id='seleall']")
                self.wait_and_click(addlist)
                time.sleep(2)
                # Confirm bid
                confirmbid = self.driver.find_element_by_css_selector("a[class='btn b3'][id='gamebuy']")
                self.wait_and_click(confirmbid)
                time.sleep(3)
                # Handle pop ups after bid confirmation
                # Get last popped up dialog box, that's a bid order confirmation
                confirm_box = self.driver.find_elements_by_css_selector("button[type='button'][i-id='ok'][class='fix-ui-dialog-autofocus']")[-1]
                time.sleep(1)
                self.wait_and_click(confirm_box)
                time.sleep(3)
                # At last, we should update biddict[key][1] to the actual value we are placing a bid
                self.biddict[key][1] = self.bidreferencetable[self.biddict[key][0]]
                self.logger("Biding done with num:{0}, amount:{1}".format(str(key), str(self.biddict[key][1])))
                time.sleep(1)
        self.logger("Round:{} Policy:YFFS End bidding...".format(str(self.round)))
Ejemplo n.º 6
0
web.get(
    "http://store.nike.com/cn/zh_cn/pd/lunarepic-low-flyknit-2-%E7%94%B7%E5%AD%90%E8%B7%91%E6%AD%A5%E9%9E%8B/pid-11232563/pgid-11493486"
)

element = web.find_element_by_css_selector(
    'div.exp-pdp-size-container a.nsg-form--drop-down--label')
element.click()

time.sleep(1)

web.save_screenshot('test.png')

element = web.find_elements_by_css_selector(
    'li.nsg-form--drop-down--option')[3]
ActionChains(web).move_to_element(element).perform()
web.save_screenshot('test.png')

ActionChains(web).click(element).perform()

time.sleep(1)

web.save_screenshot('test.png')

element = web.find_element_by_css_selector(
    'button#buyingtools-add-to-cart-button')
element.click()

time.sleep(5)

web.save_screenshot('test706.png')
Ejemplo n.º 7
0
    def test_1_buy_goods(self, item):

        my_logger.info("----------开始执行用例{0},环境是{1}----------".format(
            item['case_id'], item['surroundings']))

        ip = IP[item['surroundings']]

        H5_Login_url = url(item['surroundings'])[0]
        H5_home_url = url(item['surroundings'])[1]

        buyer_phone = eval(item['data'])['buyer_phone']
        seller_phone = eval(item['data'])['seller_phone']

        # 获取绑定关系
        superior = SuperiorTemplate().superior_template_main(
            ip, item['payment_method'], item['data'], buyer_phone)

        Boss_login_url = url(item['surroundings'])[2]

        operational_setting = eval(item['operational_setting'])
        print("----------开始BOSS后台设置运营分佣比例操作----------")
        try:

            self.driver.get(Boss_login_url)
            #Boss后台设置运营分佣比例
            BossSetting(self.driver).main(ip, item['payment_method'], superior,
                                          operational_setting)

            print("----------BOSS后台运营分佣比例设置完毕----------")

        except Exception as e:
            # 截图
            self.report_dir.get_screenshot(self.driver)

            raise e  # 异常处理完后记得抛出

        finally:
            self.driver.quit()

        print("----------开始Web操作----------")
        try:
            mobile_emulation = {'deviceName': 'iPhone X'}
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_experimental_option("mobileEmulation",
                                                   mobile_emulation)
            driver = webdriver.Chrome(options=chrome_options)

            driver.get(H5_Login_url)
            self.lg = H5_LoginPage(driver)

            self.lg.login(buyer_phone)

            #定位
            time.sleep(5)
            Location().location(driver)

            buyer_identity = item['buyer_identity']
            seller_identity = item['seller_identity']

            #充值服务费,增加储备池
            if buyer_identity == "公海用户":
                if seller_identity == "个人焕商" or seller_identity == "非焕商且已绑定个人焕商":
                    driver.find_element(*MyIndex.myIndex).click()
                    time.sleep(6)

                    # # 充值
                    Recharge().recharge(driver)
                    time.sleep(2)
                    # 支付按键
                    BuyGoods(driver).pay()
                    time.sleep(2)

                    # 写回储备池和充值金额
                    user_id = eval(item['data'])["买家"]
                    reserve_fund_data = SQL(ip).reserve_fund_data(user_id)
                    DoExcel.reserve_fund(test_case_path,
                                         item['sheet_name'], item['case_id'],
                                         str(reserve_fund_data))
                    # time.sleep(5)

                    driver.get(H5_home_url)
                    time.sleep(2)

            # 选择商品
            Seach_Goods().seach_goods(driver, item['goodsname'])

            # 购买流程
            BuyGoods(driver).BuyGood(item['payment_method'])
            time.sleep(3)

            # 卖家操作
            driver.get(H5_Login_url)
            lg = H5_LoginPage(driver)
            lg.login(seller_phone)
            time.sleep(2)
            driver.get(H5_home_url)
            time.sleep(2)
            driver.find_element(*MyIndex.myIndex).click()
            time.sleep(2)
            # 滚动至元素【销售订单】可见,点击
            ActionChains(driver).move_to_element(
                driver.find_element(*MyIndex.saleOrderList)).perform()
            driver.execute_script('window.scrollBy(0,500)')
            time.sleep(2)
            driver.find_element(*MyIndex.saleOrderList).click()
            time.sleep(5)
            # 确认订单
            WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located(
                    (MyIndex.confirm_Order))).click()
            time.sleep(6)

            # 根据商品名判断流程
            if "实物商品" in item['goodsname']:
                ReceiptDelivery(driver).entity_good(H5_Login_url, buyer_phone)

            elif "本地服务" in item['goodsname']:
                ReceiptDelivery(driver).coupon_good(H5_Login_url, H5_home_url,
                                                    buyer_phone, seller_phone)

            elif "商企服务" in item['goodsname']:
                ReceiptDelivery(driver).Business_Services(
                    H5_Login_url, buyer_phone)

            # 写回订单号
            buyerid = eval(item['data'])['买家']
            order = DoExcel.get_order(ip, test_case_path, item['sheet_name'],
                                      item['case_id'], buyerid)

            # 获取绑定关系,写回Excel
            superior = SuperiorTemplate().superior_template_main(
                ip, item['payment_method'], item['data'], buyer_phone)
            DoExcel.superior(test_case_path, item['sheet_name'],
                             item['case_id'], str(superior))

            # 获取上级分佣比例,写回Excel
            proportion = SuperiorTemplate().fenyong_template_main(
                ip, item['payment_method'], superior)
            DoExcel.fenyong_bili(test_case_path, item['sheet_name'],
                                 item['case_id'], str(proportion))

            if buyer_identity == "公海用户":
                if seller_identity == "个人焕商" or seller_identity == "非焕商且已绑定个人焕商":
                    # 跳回卖家,解除伙伴绑定
                    driver.get(H5_Login_url)
                    lg = H5_LoginPage(driver)
                    if seller_identity == "个人焕商":
                        lg.login(seller_phone)
                    elif seller_identity == "非焕商且已绑定个人焕商":
                        bangding_phone = eval(item['data'])['bangding_phone']
                        lg.login(bangding_phone)
                    time.sleep(2)
                    driver.get(H5_home_url)
                    time.sleep(2)
                    driver.find_element(*MyIndex.myIndex).click()
                    time.sleep(2)
                    driver.find_element(*MyIndex.myPartner).click()
                    time.sleep(3)
                    # 解绑
                    UntiePartner().untie_partner(driver, item['surroundings'])

            my_logger.info("----------前端操作执行完毕----------")

            ip = IP[item['surroundings']]
            data = eval(item['data'])

            buyer_id = data['买家']

            # 查询买家是否绑定销售/业务焕商/TCO
            if item['payment_method'] in ["易贝", "易贝券"]:
                # 获取买家绑定的销售/业务焕商/TCO dict
                bind_buyer_relationship_data = BingRelationshipData(
                ).bing_relationship_data(ip, item['payment_method'], data,
                                         buyer_id)

                # 把买家上级销售/业务焕商的上级写回Excel
                DoExcel().bing_sale_id(test_case_path, item['sheet_name'],
                                       item['case_id'],
                                       str(bind_buyer_relationship_data))

            elif item['payment_method'] in ["抵工资", "家人购", "现金"]:
                bind_relationship_data = BingRelationshipData(
                ).bing_relationship_data(ip, item['payment_method'], data,
                                         buyer_id)
                bind_buyer_relationship_data = bind_relationship_data[0]
                bind_payer_relationship_data = bind_relationship_data[1]
                # 买家上级销售/业务焕商的上级,写回模板
                bind_buyer_relationship_id = {
                    "储备金二级分佣对象": bind_buyer_relationship_data,
                    "支付服务费二级分佣对象": bind_payer_relationship_data
                }
                DoExcel().bing_sale_id(test_case_path, item['sheet_name'],
                                       item['case_id'],
                                       str(bind_buyer_relationship_id))

            # 获取这笔订单应该【使用】的二级分佣比例
            transaction_second_payagent_ratio = TransactionSecondPayagentRatio(
            ).transaction_second_payagent_ratio(ip, item['payment_method'],
                                                superior, data)
            # 把这笔订单所使用的二级分佣比例写回Excel
            DoExcel().second_payagent_ratio(
                test_case_path, item['sheet_name'], item['case_id'],
                str(transaction_second_payagent_ratio))
        except Exception as e:
            # 截图
            self.report_dir.get_screenshot(driver)
            driver.quit()
            raise e  # 异常处理完后记得抛出
        # finally:
        #     driver.quit()

        try:
            my_logger.info("----------开始进行对比----------")

            ip = IP[item['surroundings']]
            if buyer_identity == "公海用户":
                if seller_identity == "个人焕商" or seller_identity == "非焕商且已绑定个人焕商":
                    charge_amount = reserve_fund_data['charge_amount']
                    reserve_fund = reserve_fund_data['reserve_fund']
                else:
                    charge_amount = None
                    reserve_fund = None
            else:
                charge_amount = None
                reserve_fund = None

            calculation_data = CalculationData().calculation_data(
                ip, item['payment_method'], item['member_level'],
                buyer_identity, seller_identity, proportion, charge_amount,
                reserve_fund, order)

            if item['payment_method'] in ["易贝", "易贝券"]:
                expected_moban = MoBan(buyer_identity, seller_identity,
                                       item['member_level'],
                                       item['payment_method'],
                                       order).expected_moban(
                                           ip, data, superior, reserve_fund,
                                           calculation_data,
                                           transaction_second_payagent_ratio,
                                           bind_buyer_relationship_data)
            elif item['payment_method'] in ["抵工资", "家人购", "现金"]:
                expected_moban = MoBan(buyer_identity, seller_identity,
                                       item['member_level'],
                                       item['payment_method'],
                                       order).expected_moban(
                                           ip, data, superior, reserve_fund,
                                           calculation_data,
                                           transaction_second_payagent_ratio,
                                           bind_buyer_relationship_data,
                                           bind_payer_relationship_data)

            # 写回Excel用
            fanhui = FanHui().fan_hui(ip, order, expected_moban)

            sql_data = SQL(ip).wallet_detail(order)

            for i in range(0, len(expected_moban)):
                self.assertEqual(expected_moban[i], sql_data[i])

            self.assertEqual(expected_moban, sql_data)
            my_logger.info("用例{0}正确!{1}".format(item['case_id'],
                                                item['title']))
            TestResult = 'Pass'
            Error = None

        except Exception as e:
            #截图
            self.report_dir.get_screenshot(driver)
            my_logger.info("用例错误!错误原因是第{0}行,{1}:".format(i + 1, e))
            TestResult = 'Failed'
            Error = "用例错误!错误原因是:第{0}行,{1}:".format(i + 1, e)
            raise e  # 异常处理完后记得抛出

        finally:  # 不管怎样都得写入Excel
            DoExcel().write_back(test_case_path, item['sheet_name'],
                                 item['case_id'] + 1, str(fanhui[0]),
                                 str(fanhui[2]), str(expected_moban),
                                 str(sql_data), TestResult, str(Error))

        # time.sleep(2)
        my_logger.info("----------对比结束----------")
        my_logger.info("----------用例{0}执行完毕----------".format(item['case_id']))
Ejemplo n.º 8
0
def play(driver, sf):
    global initial_board
    global initial_coord

    color = check_color(driver)

    board = initial_board
    coord = initial_coord

    if color == "white":
        p = driver.find_element_by_xpath(
            "//div[contains(@class, 'square-11')]")
    else:
        p = driver.find_element_by_xpath(
            "//div[contains(@class, 'square-88')]")
    print(p.location)
    for x in range(SizeBoard):
        for y in range(SizeBoard):
            coord[x][y] = (p.location['x'] + p.size['height'] * x,
                           p.location['y'] - p.size['height'] * y)

    castleB = True
    castleW = True
    cw = "KQ"
    cb = "kq"
    castle = cw + cb
    coups = 1
    Game = True

    while (Game):
        action = ActionChains(driver)
        ok = True
        # t1, t2 = clock_catch(driver)
        print("Enter OK loop")
        while (ok):
            if end_game(driver):
                Game = False
                break
            if check_turn(driver, color=color):
                print("Enter Check_Turn loop")
                sleep(0.1)
                new_board = board_state(driver)
                # for i in reversed(new_board):
                #     print(i)
                break
            sleep(0.05)

        if Game:
            board = new_board

            fen = board_to_fen(board, coups, castle,
                               color)  # board_to_fen(board,coups,castle,color)
            print("FEN:", fen)
            sf.set_fen_position(fen)
            print("Check BM loop")
            times = clock_catch(driver)
            if times[1] < 60:
                bm = sf.get_best_move_time(300)
            elif times[1] < 90:
                bm = sf.get_best_move_time(500)
            else:
                if random() < 0.25:  #bad moves
                    bm = sf.get_best_move()
                else:
                    bm = sf.get_best_move_time(1000)
            print("Best Move:", bm)

            src = bm[:2]
            dst = bm[2:]

            board, eat = board_modif(board, src, dst)
            print("Catch positions")
            p = sf_pos_to_chesscom_piece(driver, src)
            src = pos_to_coord(src, coord, color)
            dst = pos_to_coord(dst, coord, color)
            diff = calcul_offset(src, dst)
            # times = clock_catch(driver)
            # print(times)
            print("Pause")
            if not eat and coups > 5:
                time_to_move(times)
            else:
                sleep(randint(300, 600) / 1000)
            print("Catch mv_cnt")
            mcnt = move_cnt(driver)
            print("Moving the piece")
            deplace_bool = 5
            while (deplace_bool > 0):
                try:
                    deplace(action, p, diff)
                    break
                except:
                    deplace_bool -= 1
                    sleep(0.5)
            start_move = time.time()
            while (mcnt <= move_cnt(driver)):
                if end_game(driver):
                    Game = False
                    break
                sleep(0.05)
                if (time.time() - start_move > 3):
                    print("Move not Done")
                    break
            if Game:
                print("Castling check")
                coups += 1
                if castleW:
                    cw = check_castle_white(board, cw)
                    if cw == "":
                        casleW = False

                if castleB:
                    cb = check_castle_black(board, cb)
                    if cb == "":
                        casleB = False
                castle = cw + cb
                if castle == "":
                    castle = "-"

                for i in reversed(board):
                    print(i)

    print("END GAME")
Ejemplo n.º 9
0
def play_computer(driver, sf):
    global initial_board
    global initial_coord

    color = check_color(driver)
    print(color)

    board = initial_board
    coord = initial_coord

    if color == "white":
        p = driver.find_element_by_xpath(
            "//div[contains(@class, 'square-11')]")
    else:
        p = driver.find_element_by_xpath(
            "//div[contains(@class, 'square-88')]")
    print(p.location)
    for x in range(SizeBoard):
        for y in range(SizeBoard):
            coord[x][y] = (p.location['x'] + p.size['height'] * x,
                           p.location['y'] - p.size['height'] * y)

    castleB = True
    castleW = True
    cw = "KQ"
    cb = "kq"
    castle = cw + cb
    coups = 1
    Game = True

    while (Game):
        action = ActionChains(driver)
        ok = True
        while (ok):
            if end_game(driver):
                Game = False
                break
            if check_turn(driver, color=color):
                sleep(0.1)
                new_board = board_state(driver)
                for i in reversed(new_board):
                    print(i)
                break
            sleep(0.05)

        if Game:
            board = new_board

            fen = board_to_fen(board, coups, castle,
                               color)  # board_to_fen(board,coups,castle,color)
            print("FEN:", fen)
            sf.set_fen_position(fen)

            bm = sf.get_best_move()
            print("Best Move:", bm)

            src = bm[:2]
            dst = bm[2:]

            board, eat = board_modif(board, src, dst)

            p = sf_pos_to_chesscom_piece(driver, src)
            src = pos_to_coord(src, coord, color)
            dst = pos_to_coord(dst, coord, color)
            diff = calcul_offset(src, dst)

            sleep(randint(300, 600) / 1000)
            mcnt = move_cnt(driver)
            # print("Moving from ",bm[:2],bm[2:])
            deplace(action, p, diff)
            # print("Wait moving")
            while (mcnt == move_cnt(driver)):
                if end_game(driver):
                    Game = False
                    break
                sleep(0.05)
            if Game:
                # print("Move done")
                coups += 1
                if castleW:
                    cw = check_castle_white(board, cw)
                    if cw == "":
                        casleW = False

                if castleB:
                    cb = check_castle_black(board, cb)
                    if cb == "":
                        casleB = False
                castle = cw + cb
                if castle == "":
                    castle = "-"

                for i in reversed(board):
                    print(i)

    print("END GAME")
Ejemplo n.º 10
0
driver.get("https://www.nike.com/launch/")
time.sleep(10)  #log in to nike app
start_url = 'https://www.nike.com/launch/?s=upcoming'
driver.get(start_url)
shoe = wait.until(
    EC.element_to_be_clickable(
        (By.XPATH, '//img[@title="AIR FORCE 1 UTILITY"]')))
shoe.click()
driver.execute_script("window.scrollTo(0,1000)")
size = wait.until(
    EC.element_to_be_clickable((
        By.CSS_SELECTOR,
        'div.label.border-medium-grey.ncss-brand.u-uppercase.pb3-sm.pb3-lg.prl5-sm.pt3-sm.pt3-lg.pl5-sm.u-full-width'
    )))
size.click()
action = ActionChains(driver).move_to_element_with_offset(size, 100, 350)
action.click()
action.perform()
cart_btn = wait.until(
    EC.element_to_be_clickable((
        By.CSS_SELECTOR,
        'button.ncss-brand.ncss-btn-black.pb3-sm.prl5-sm.pt3-sm.u-uppercase.u-full-width'
    )))
#cart_btn = driver.find_element_by_xpath("/html/body/div[2]/div/div/div[1]/div/div[2]/div[2]/div/section[1]/div[2]/aside/div/div[2]/div/div[2]/div[2]/button")
cart_btn.click()
check_out_btn = wait.until(
    EC.element_to_be_clickable(
        (By.XPATH, "/html/body/div[2]/div/div/div[2]/div/div/div/div/div[3]")))
check_out_btn.click()
guest_checkout = wait.until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="qa-guest-checkout"]')))
Ejemplo n.º 11
0
 def __init__(self, driver):
     self.driver = driver
     self.wait = WebDriverWait(self.driver, 15)
     self.actions = ActionChains(self.driver)
     self.alerts = Alert(self.driver)
Ejemplo n.º 12
0
 def fill_checkbox_with_link(self, how, what):
     assert self.is_element_present(
         how, what), "Agreement checkbox is not presented"
     agreement_checkbox = self.browser.find_element(how, what)
     ActionChains(self.browser).move_to_element_with_offset(
         agreement_checkbox, 10, 10).click().perform()
Ejemplo n.º 13
0
    def play_media(self,url):
        wait = WebDriverWait(self.driver, 30)
        action_chains = ActionChains(self.driver)

        self.driver.get(url)
        # 点击视频确保进入视频界面(若出现问题增多可以改换bs4或者re分析)
        media_tag = ['@title="视频"', '@title="视频 "', '@title="微课"', 'last()-1']
        try:
            wait.until(EC.presence_of_element_located(
                (By.XPATH, '//div[@class="left"]/div/div[@class="main"]/div[@class="tabtags"]')))
            for tag in media_tag:
                try:
                    bt = self.driver.find_element_by_xpath(
                        '//div[@class="left"]/div/div[@class="main"]/div[@class="tabtags"]/span['+tag+']')
                    break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    pass
            sleep(5)
            self.driver.execute_script("arguments[0].scrollIntoView();arguments[0].click();", bt)
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            pass
        
        try:
            wait.until(EC.presence_of_element_located((By.XPATH,'//div[@class="switchbtn"]')))
            switch_btn=self.driver.find_element_by_xpath('//div[@class="switchbtn"]')
            action_chains.move_to_element(switch_btn)
            switch_btn.click()
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            pass

        try:
            wait.until(EC.presence_of_element_located((By.XPATH, '//iframe')))
            iframe = self.driver.find_element_by_xpath('//iframe')
            self.driver.switch_to.frame(iframe)
            sleep(1)
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            print(COLOR.NOTE, ' no videos,continue~', COLOR.END, file=self._out_fp)
            #log_fp.write(' no videos,continue~\n')
            return

        # 多视频处理
        try:
            video_num = self.driver.execute_script(
                "window.scrollTo(0,document.body.scrollHeight);return document.getElementsByClassName('ans-job-icon').length")
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            video_num = self.driver.execute_script(
                "return document.getElementsByClassName('ans-job-icon').length")
        try:
            self.driver.execute_script("window.scrollTo(0,0)")
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            pass

        wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="ans-cc"]')))
        ans_cc = self.driver.find_element_by_xpath('//div[@class="ans-cc"]')
        for i in range(3):
            try:
                h5_text = ans_cc.get_attribute('innerHTML')
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                sleep(1)
        video_road = PlayMedia.get_road(h5_text, video_num)  # bs4处理得到各个视频路径

        print(COLOR.DISPLAY, ' there are ' + str(video_num) + ' media in this section:', COLOR.END, file=self._out_fp)
        #log_fp.write(' there are ' + str(video_num) + ' videos in this section:\n')

        # 开始播放所有视频
        first_road = '//div[@class="ans-cc"]'

        for v_num in range(1, video_num + 1):
            # log
            #self.driver.refresh()
            self.driver.switch_to.default_content()
            for i in range(5):
                try:
                    wait.until(EC.presence_of_element_located((By.XPATH, '//iframe')))
                    iframe = self.driver.find_element_by_xpath('//iframe')
                    self.driver.switch_to.frame(iframe)
                    break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    sleep(i+0.5)

            print(COLOR.DISPLAY, ' go ' + str(v_num) + ':', COLOR.END, file=self._out_fp)
            #log_fp.write(' go ' + str(v_num) + ':\n')
            # 拖动滚动条
            #self.driver.execute_script("window.scrollTo(0,arguments[0])", 400 + 700 * (v_num - 1))
            sleep(2)

            goal_road = first_road + video_road[v_num - 1]
            # 查看是否有任务点标识并查看是或否已经完成该任务点
            try:
                flag = self.driver.find_element_by_xpath(goal_road)
                self.driver.execute_script(
                    '''var goal=document.evaluate(arguments[0],document).iterateNext();goal.scrollIntoView();''', goal_road)
                sleep(5)
                icon_flag = 1
                nowflag = flag.get_attribute('class')
                if 'finished' in nowflag:
                    print(COLOR.OK + ' Well! the video is already finished! continue~' + COLOR.END, file=self._out_fp)
                    #log_fp.write(' Well! the video is already finished! continue~' + '\n')
                    self._end = 0
                    # 如果视频任务已完成,访问下一个视频
                    continue
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                #print(traceback.format_exc())
                icon_flag = 0

            #print(1)
            # try:
            iframe_flag = 0
            for i in range(10):
                try:
                    wait.until(EC.presence_of_element_located((By.XPATH, goal_road + '/iframe')))
                    iframe = self.driver.find_element_by_xpath(goal_road + '/iframe')
                    self.driver.switch_to.frame(iframe)
                    iframe_flag = 1
                    sleep(2)
                    break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    #print(traceback.format_exc())
                    # log
                    sleep(i+1)
            if iframe_flag == 0:
                print(COLOR.ERR+"  can't into the video,continue"+COLOR.END, file=self._out_fp)
                continue

            #print(2)

            try:
                ppt_num = eval(self.driver.execute_script("return document.getElementsByClassName('all')[0].innerText"))
                for i in range(0, ppt_num):
                    self.driver.execute_script("document.getElementsByClassName('mkeRbtn')[0].click()")
                    sleep(1)
                continue
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                pass

            #print(2.5)

            # 通过js代码开始视频播放
            play_ok = 0
            for i in range(3):
                try:
                    self.driver.execute_script(
                        """
                        var video=document.querySelector('video');video.scrollIntoView();video.play();
                        video.onmouseout=function(){return false;}
                        """)
                    play_ok = 1
                    sleep(2)
                    self.driver.execute_script("document.querySelector('video').autoplay=true;")
                    self.driver.execute_script("document.querySelector('video').play();")
                    self.driver.execute_script(
                        "document.querySelector('video').playbackRate=arguments[0];document.querySelector('video').defaultPlaybackRate=arguments[0]", PlayMedia.rate)
                    sleep(1)
                    #self.driver.execute_script("document.querySelector('video').load();")
                    break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    #print(format_exc())
                    send_err(format_exc())
                    sleep(i+1)
            #print(3)

            audio = 0
            if play_ok == 0:
                for i in range(3):
                    try:
                        self.driver.execute_script(
                            "var audio=document.querySelector('audio');audio.scrollIntoView();audio.play();audio.onmouseout=function(){return false;}")
                        play_ok = 1
                        audio = 1
                        self.driver.execute_script("document.querySelector('audio').autoplay=true;")
                        self.driver.execute_script(
                            "document.querySelector('audio').playbackRate=arguments[0];document.querySelector('audio').defaultPlaybackRate=arguments[0]", PlayMedia.rate)
                        #self.driver.execute_script("document.querySelector('audio').load();")
                        break
                    except KeyboardInterrupt:
                        raise KeyboardInterrupt
                    except:
                        sleep(i+1)
            if audio == 1:
                media_type = 'audio'
            else:
                media_type = 'video'

            #print(media_type)

            if play_ok == 0:
                # 未播放成功
                self.driver.switch_to.parent_frame()
                print(COLOR.DISPLAY+' this is not a media, go ahead!'+COLOR.END, file=self._out_fp)
                #log_fp.write(" this is not a video, go ahead!\n")
                continue
            else:
                # 开倍速 & 获取时间信息
                sleep(2)
                for i in range(5):
                    total_tm = self.driver.execute_script(
                        "return document.querySelector(arguments[0]).duration", media_type)
                    #print(total_tm)
                    now_tm = self.driver.execute_script(
                        "return document.querySelector(arguments[0]).currentTime", media_type)
                    #print(now_tm)
                    self.driver.execute_script("document.querySelector(arguments[0]).play();", media_type)
                    if total_tm != None and now_tm != None:
                        break
                    else:
                        sleep(i+1)
                total_tm = int(total_tm)
                now_tm = int(now_tm)
                need_tm = total_tm-now_tm
                print("   now_tm:", now_tm, '\t', "total_tm:", total_tm, '\t', "need_tm:", need_tm, file=self._out_fp)

            #print(4)

            real_time = 0
            while 1:
                real_time += 10
                try:
                    now_tm = self.driver.execute_script(
                        "return document.querySelector(arguments[0]).currentTime", media_type)
                    need_tm = total_tm-int(now_tm)
                    self.driver.execute_script("document.querySelector(arguments[0]).play();", media_type)
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    pass
                # 交互
                progress = (total_tm-need_tm)*100/total_tm
                print(COLOR.OK+"   progress:{0:.2f}%\trest:{1}         ".format(progress,
                                                                                need_tm)+COLOR.END, file=self._out_fp, end="\r")
                self._out_fp.flush()

                # 剩余时间<5min则间隔性检验任务是否已完成
                if (icon_flag == 1 and need_tm <= 300):
                    self.driver.switch_to.parent_frame()
                    flag = self.driver.find_element_by_xpath(goal_road)
                    nowflag = flag.get_attribute('class')
                    self.driver.switch_to.frame(self.driver.find_element_by_xpath(goal_road + '/iframe'))
                    if 'finished' in nowflag:
                        print(COLOR.OK, ' Well!the video is finished ahead of time! continue~', COLOR.END, file=self._out_fp)
                        #log_fp.write(' Well!the video is finished ahead of time! continue~' + '\n')
                        sleep(10)
                        break

                if need_tm <= 2 or real_time > (total_tm+100):
                    print(COLOR.OK, ' Well!the video is finished! continue~', COLOR.END, file=self._out_fp)
                    #log_fp.write(' Well!the video is finished! continue~' + '\n')
                    sleep(10)
                    break

                # 自动检测答题
                pre = 1  # 选项默认值
                try:
                    uls = self.driver.find_element_by_xpath(
                        '//div[@class="x-container ans-timelineobjects x-container-default"]/span/div/div/ul')
                    que_type = self.driver.find_element_by_xpath(
                        '//div[@class="ans-videoquiz-title"]').get_attribute('textContent')
                    #log_fp.write('que_type:' + que_type + '\n')
                    que_type = re_search(r'[[]([\w\W]+?)[]]', que_type).group(1)
                    #log_fp.write('      monitor question,' + que_type + '\n')
                    if "多选题" in que_type:
                        # print(uls.find_elements_by_xpath('//li[@class="ans-videoquiz-opt"]'))
                        opt_num = len(uls.find_elements_by_xpath('//li[@class="ans-videoquiz-opt"]'))  # 选项个数
                        #print(opt_num,file=self._out_fp)
                        for opt_i in range(2, opt_num + 1):  # 选择个数2,3,4,……
                            fin_que = 1
                            for opt_j in range(1, opt_num - opt_i + 2):  # 起始位置
                                #print('      select:',file=self._out_fp)
                                for opt_k in range(0, opt_i):  # 个数
                                    option = uls.find_element_by_xpath('//li[' + str(opt_j + opt_k) + ']/label/input')
                                    self.driver.execute_script("arguments[0].click();", option)
                                sleep(5)
                                bn = self.driver.find_element_by_xpath(
                                    '//div[@class="x-container ans-timelineobjects x-container-default"]/span/div/div/div[2]')
                                self.driver.execute_script("arguments[0].click();", bn)
                                try:
                                    self.driver.switch_to_alert().accept()
                                except:
                                    fin_que = 0
                                    break
                                try:
                                    while 1:  # 多选题答错会弹出不止一个alert
                                        self.driver.switch_to_alert().accept()
                                except:
                                    sleep(0.5)

                                for opt_k in range(0, opt_i):  # 个数
                                    option = uls.find_element_by_xpath('//li[' + str(opt_j + opt_k) + ']/label/input')
                                    self.driver.execute_script("arguments[0].click();", option)
                                sleep(5)
                                bn = self.driver.find_element_by_xpath(
                                    '//div[@class="x-container ans-timelineobjects x-container-default"]/span/div/div/div[2]')
                                self.driver.execute_script("arguments[0].click();", bn)
                                try:
                                    while 1:  # 多选题答错会弹出不止一个alert
                                        self.driver.switch_to_alert().accept()
                                except:
                                    sleep(0.5)
                                sleep(0.5)

                            if fin_que == 0:
                                break
                        #log_fp.write('      solve the question\n')
                        sleep(10)
                    else:
                        while 1:
                            try:
                                option = uls.find_element_by_xpath('//li[' + str(pre) + ']/label/input')
                                self.driver.execute_script("arguments[0].click();", option)
                                # action_chains.move_to_element(option)
                                # option.click()
                                #log_fp.write('      select ' + chr(pre + 64) + '\n')
                                bn = self.driver.find_element_by_xpath(
                                    '//div[@class="x-container ans-timelineobjects x-container-default"]/span/div/div/div[2]')
                                self.driver.execute_script("arguments[0].click();", bn)
                                # action_chains.move_to_element(bn)
                                # bn.click()
                                # action_chains.click(bn)
                                try:
                                    while 1:
                                        self.driver.switch_to_alert().accept()
                                except KeyboardInterrupt:
                                    raise KeyboardInterrupt
                                except:
                                    sleep(0.3)
                                    pre += 1
                            except KeyboardInterrupt:
                                raise KeyboardInterrupt
                            except:
                                #log_fp.write('      solve the question\n')
                                sleep(10)
                                break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:  # 10s延时
                    sleep(10)

            print(COLOR.OK+' finish the video                     '+COLOR.END, file=self._out_fp)
Ejemplo n.º 14
0
    def update(self):

        for i in range(len(self.obj_id)):
            obj_id = self.obj_id[i]
            totalArea = self.area[i]
            minArea = self.minarea[i]
            floorNumber = self.floornumber[i]
            floorCount = self.floorcount[i]
            ceilingHeight = self.ceilingheight[i]
            columnGrid = self.columngrid[i]
            floorMaterial = self.floormaterial[i]
            conditionType = self.conditiontype[i]
            gatesType = self.gatestype[i]
            waterPipesCount = self.waterpipescount[i]
            electricityPower = self.electricitypower[i]
            parkingLocationType = self.parkinglocationtype[i]
            parkingType = self.parkingtype[i]
            placesCount = self.placescount[i]
            priceEntry = self.priceentry[i]
            priceCurrency = self.pricecurrency[i]
            vatType = self.vattype[i]
            leaseType = self.leasetype[i]
            minLeaseTerm = self.minleaseterm[i]
            hasGracePeriod = self.hasgraceperiod[i]
            securityDeposit = self.securitydeposit[i]
            prepayType = self.prepaytype[i]

            print('Star updating object with id', obj_id)

            object_link = self.object_link.format(obj_id)
            self.driver.get(object_link)

            try:
                total_area_input = self.driver.find_element_by_xpath(
                    "//input[@name='totalArea']")
                total_area_input.clear()
                total_area_input.send_keys(totalArea)

                print('totalArea ', totalArea, 'send')

                time.sleep(3)

            except Exception as e:
                print('No totalArea', e)

            try:
                min_area_input = self.driver.find_element_by_xpath(
                    "//input[@name='minArea']")
                min_area_input.clear()
                min_area_input.send_keys(minArea)
                print('minArea ', minArea, 'send')
                time.sleep(3)

            except Exception as e:
                print('No minArea', e)

            try:
                floor_number_input = self.driver.find_element_by_xpath(
                    "//input[@name='floorNumber']")
                floor_number_input.clear()
                floor_number_input.send_keys(floorNumber)
                print('floorNumber ', floorNumber, 'send')
                time.sleep(3)

            except Exception as e:
                print('No floorNumber', e)

            try:
                floor_count_input = self.driver.find_element_by_xpath(
                    "//input[@name='floorsCount']")
                floor_count_input.clear()
                floor_count_input.send_keys(floorCount)
                print('floorCount ', floorCount, 'send')
                time.sleep(3)

            except Exception as e:
                print('No floorCount', e)

            try:
                ceiling_height_input = self.driver.find_element_by_xpath(
                    "//input[@name='building.ceilingHeight']")
                ceiling_height_input.clear()
                ceiling_height_input.send_keys(ceilingHeight)
                print('ceilingHeight ', ceilingHeight, 'send')

                time.sleep(3)

            except Exception as e:
                print('No ceilingHeight', e)

            try:
                column_grid_input = self.driver.find_element_by_xpath(
                    "//input[@name='columnGrid']")
                column_grid_input.clear()
                column_grid_input.send_keys(columnGrid)
                print('columnGrid', columnGrid, 'send')

                time.sleep(3)

            except Exception as e:
                print('No columnGrid', e)

            try:
                floor_material_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                floor_material_select_find[1].click()

                floor_material_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown__item')]")

                if 'полимерный' in floorMaterial:
                    floor_material_select_from_list[0].click()
                    print('floorMaterial', floorMaterial, 'clicked')
                elif 'бетон' in floorMaterial:
                    floor_material_select_from_list[1].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'линолеум' in floorMaterial:
                    floor_material_select_from_list[2].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'асфальт' in floorMaterial:
                    floor_material_select_from_list[3].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'плитка' in floorMaterial:
                    floor_material_select_from_list[4].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'наливной' in floorMaterial:
                    floor_material_select_from_list[5].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'железобетонный' in floorMaterial:
                    floor_material_select_from_list[6].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'дерево' in floorMaterial:
                    floor_material_select_from_list[7].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                elif 'ламинат' in floorMaterial:
                    floor_material_select_from_list[8].click()
                    print('floorMaterial ', floorMaterial, 'clicked')
                else:
                    print('No floorMaterial')

                time.sleep(3)

            except Exception as e:
                print('Some floorMaterial Exception', e)

            try:
                condition_type_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                condition_type_select_find[2].click()

                condition_type_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown__item')]")

                if 'Типовой ремонт' in conditionType:
                    condition_type_select_from_list[0].click()
                    print('conditionType', conditionType, 'clicked')
                elif 'Требуется капитальный ремонт' in conditionType:
                    condition_type_select_from_list[1].click()
                    print('conditionType ', conditionType, 'clicked')

                elif 'Требуется косметический ремонт' in conditionType:
                    condition_type_select_from_list[2].click()
                    print('conditionType ', conditionType, 'clicked')

                else:
                    print('No conditionType')

            except Exception as e:
                print('Some conditionType Exception', e)
            time.sleep(3)

            try:
                gates_type_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                gates_type_select_find[3].click()

                gates_type_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown__item')]")

                if 'На пандусе' in gatesType:
                    gates_type_select_from_list[0].click()
                    print('gatesType ', gatesType, 'clicked')
                elif 'Докового типа' in gatesType:
                    gates_type_select_from_list[1].click()
                    print('gatesType ', gatesType, 'clicked')
                elif 'На нулевой отметке' in gatesType:
                    gates_type_select_from_list[2].click()
                    print('gatesType ', gatesType, 'clicked')
                else:
                    print('No gatesType')
                time.sleep(3)
            except Exception as e:
                print('Some gatesType Exception', e)

            try:
                water_pipes_count_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                water_pipes_count_select_find[4].click()

                water_pipes_count_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown__item')]")

                if type(waterPipesCount) is str and 'нет' in waterPipesCount:
                    water_pipes_count_select_from_list[0].click()
                    print('waterPipesCount', waterPipesCount, 'clicked')
                elif 1 == waterPipesCount:
                    water_pipes_count_select_from_list[1].click()
                    print('waterPipesCount', waterPipesCount, 'clicked')
                elif 2 == waterPipesCount:
                    water_pipes_count_select_from_list[2].click()
                    print('waterPipesCount', waterPipesCount, 'clicked')
                elif 3 == waterPipesCount:
                    water_pipes_count_select_from_list[3].click()
                    print('waterPipesCount', waterPipesCount, 'clicked')
                elif 4 == waterPipesCount:
                    water_pipes_count_select_from_list[4].click()
                    print('waterPipesCount', waterPipesCount, 'clicked')
                else:
                    print('No waterPipesCount')
                time.sleep(3)
            except Exception:
                print('Some waterPipesCount Exception')

            try:
                electricity_power_input = self.driver.find_element_by_xpath(
                    "//input[@name='electricity.power']")
                electricity_power_input.clear()
                electricity_power_input.send_keys(electricityPower)
                print('electricityPower', electricityPower, 'send')

                time.sleep(3)

            except Exception as e:
                print('No electricityPower', e)

            try:
                parking_location_type_buttons_list = self.driver.find_elements_by_xpath(
                    "//div[@name='building.parking.locationType']//div[contains(@class, 'cui-switcher__part')]"
                )

                if 'На территории объекта' in parkingLocationType:

                    parking_location_type_buttons_list[0].click()
                    print('parkingLocationType ', parkingLocationType, 'send')

                elif 'За территорией объекта' in parkingLocationType:

                    parking_location_type_buttons_list[1].click()
                    print('parkingLocationType ', parkingLocationType, 'send')

                else:
                    print('No parkingLocationType')

                time.sleep(3)

            except Exception as e:
                print('Some parkingLocationType Expection', e)

            try:
                parking_purpose_type_buttons_list = self.driver.find_elements_by_xpath(
                    "//div[@name='building.parking.purposeType']//div[contains(@class, 'cui-switcher__part')]"
                )

                if 'Для грузового транспорта' in parkingType:

                    parking_purpose_type_buttons_list[0].click()
                    print('parkingType ', parkingType, 'send')

                elif 'Для легковесного транспорта' in parkingType:

                    parking_purpose_type_buttons_list[1].click()
                    print('parkingType ', parkingType, 'send')

                else:
                    print('No parkingType')

                time.sleep(3)

            except Exception as e:
                print('Some parkingType Expection', e)

            try:
                places_count_input = self.driver.find_element_by_xpath(
                    "//input[@name='building.parking.placesCount']")
                places_count_input.clear()
                places_count_input.send_keys(placesCount)
                print('placesCount ', placesCount, 'send')

                time.sleep(3)

            except Exception as e:
                print('No placesCount', e)

            try:
                price_entry_input = self.driver.find_element_by_xpath(
                    "//input[@name='building.parking.priceEntry']")
                price_entry_input.clear()
                price_entry_input.send_keys(priceEntry)
                print('priceEntry ', priceEntry, 'send')

                time.sleep(3)

            except Exception as e:
                print('No priceEntry', e)

            try:
                price_currency_input = self.driver.find_element_by_xpath(
                    "//input[@name='bargainTerms.price']")
                price_currency_input.clear()
                price_currency_input.send_keys(priceCurrency)
                print('priceCurrency ', priceCurrency, 'send')
                time.sleep(3)

            except Exception as e:
                print('No priceCurrency', e)

            try:
                vat_type_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                vat_type_select_find[7].click()

                vat_type_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown')]")
                # print(vatType, 'datatype', type(vatType))

                if vatType == 1:
                    vat_type_select_from_list[0].click()
                    print('vatType ', vatType, 'clicked')
                elif vatType == 2:
                    vat_type_select_from_list[1].click()
                    print('vatType ', vatType, 'clicked')
                elif vatType == 3:
                    vat_type_select_from_list[2].click()
                    print('vatType ', vatType, 'clicked')
                else:
                    print('No vatType')
                time.sleep(3)

            except Exception as e:
                print('Some vatType Exception', e)

            try:
                min_lease_term_input = self.driver.find_element_by_xpath(
                    "//input[@name='bargainTerms.minLeaseTerm']")
                min_lease_term_input.clear()
                min_lease_term_input.send_keys(minLeaseTerm)
                print('minLeaseTerm ', minLeaseTerm, 'send')

                time.sleep(3)

            except Exception:
                print('No minLeaseTerm')

            try:
                lease_type_type_buttons_list = self.driver.find_elements_by_xpath(
                    "//div[@name='bargainTerms.leaseType']//div[contains(@class, 'cui-switcher__part')]"
                )

                # print(lease_type_type_buttons_list)

                if 'Прямая аренда' in leaseType:

                    lease_type_type_buttons_list[0].click()
                    print('leaseType ', leaseType, 'send')

                elif 'Субаренда' in leaseType:

                    lease_type_type_buttons_list[1].click()
                    print('leaseType ', leaseType, 'send')

                else:
                    print('No leaseType')

            except Exception as e:
                print('Some leaseType Expection', e)

            try:
                security_deposit_input = self.driver.find_element_by_xpath(
                    "//input[@name='bargainTerms.securityDeposit']")
                security_deposit_input.clear()
                security_deposit_input.send_keys(securityDeposit)
                print('securityDeposit ', securityDeposit, 'send')

                time.sleep(3)

            except Exception as e:
                print('No securityDeposit', e)

            try:
                # print('prepayType == ', prepayType)
                prepay_type_select_find = self.driver.find_elements_by_xpath(
                    "//button[@class='cui-button cui-button_look_gray']")
                prepay_type_select_find[8].click()

                time.sleep(2)

                if '10 месяцев' or '11 месяцев' or '1 год' in prepayType:
                    scroll = self.driver.find_element_by_xpath(
                        "//ul[@class='cui-dropdown__menu']")
                    hover = ActionChains(self.driver).move_to_element(scroll)
                    hover.perform()
                    time.sleep(3)

                prepay_type_select_from_list = self.driver.find_elements_by_xpath(
                    "//li[contains(@class, 'cui-dropdown__item')]")
                # prepay_type_select_from_list[10].click()
                print('11 месяцев' in prepayType)

                if '11 месяцев' in prepayType:
                    prepay_type_select_from_list[10].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '1 месяц' in prepayType:
                    prepay_type_select_from_list[0].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '2 месяца' in prepayType:
                    prepay_type_select_from_list[1].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '3 месяца' in prepayType:
                    prepay_type_select_from_list[2].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '4 месяца' in prepayType:
                    prepay_type_select_from_list[3].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '5 месяцев' in prepayType:
                    prepay_type_select_from_list[4].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '6 месяцев' in prepayType:
                    prepay_type_select_from_list[5].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '7 месяцев' in prepayType:
                    prepay_type_select_from_list[6].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '8 месяцев' in prepayType:
                    prepay_type_select_from_list[7].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '9 месяцев' in prepayType:
                    prepay_type_select_from_list[8].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '10 месяцев' in prepayType:
                    prepay_type_select_from_list[9].click()
                    print('prepayType ', prepayType, 'clicked')
                elif '1 год' in prepayType:
                    prepay_type_select_from_list[11].click()
                    print('prepayType ', prepayType, 'clicked')
            except Exception as e:
                print('No prepayType', e)

            time.sleep(3)

            try:
                grace_period_type_buttons_list = self.driver.find_elements_by_xpath(
                    "//div[@name='hasGracePeriod']//div[contains(@class, 'cui-switcher__part')]"
                )
                # print(grace_period_type_buttons_list)

                if 'Да' in hasGracePeriod:

                    grace_period_type_buttons_list[0].click()
                    print('hasGracePeriod ', hasGracePeriod, 'send')

                elif 'Нет' in hasGracePeriod:

                    grace_period_type_buttons_list[1].click()
                    print('hasGracePeriod ', hasGracePeriod, 'send')

                else:
                    print('No hasGracePeriod')

            except Exception as e:
                print('Some hasGracePeriod Expection', e)

        print('Object', obj_id, ' updated')
        time.sleep(5)
Ejemplo n.º 15
0
def scrape():
    header = []
    #sets up Driver

    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('--incognito')
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')

    #goes to webpage and collects data

    driver = webdriver.Chrome('/Users/Aditya/Desktop/chromedriver',
                              options=options)
    driver.get("https://www.realclearpolitics.com/coronavirus/")
    element = driver.find_element_by_xpath(
        '//*[@id="covid_totals_table"]/div/div/table/tfoot/tr/td/button')
    actions = ActionChains(driver)
    actions.move_to_element(element).click().perform()
    html = driver.page_source
    soup = BeautifulSoup(html, "lxml")

    #print(soup)

    #finds table and extracts data

    table = soup.find('table')
    tableHeader = table.find_all('th')
    information = table.find_all('td')

    #gets header info
    for head in tableHeader:
        header.append(head.text)

    #gets global info

    globalTable = information[:10]
    globalinfo = []
    temp = []
    for gInfo in globalTable:
        if gInfo.text != 'Deaths':
            temp.append(gInfo.text)
    globalinfo.append(temp)

    #gets country info

    local = []
    countryInfo = []
    countryTable = information[11:]
    count = 0

    for x in countryTable:
        if (count < 10):
            local.append(x.text)
            count += 1

        if (count == 10):
            count = 0
            countryInfo.append(local)
            local = []
    driver.quit()
    return countryInfo, globalinfo, header
Ejemplo n.º 16
0
    def test_submitting_to_interviewdb(self):
        self.browser.get(
            'http://*****:*****@id="root"]/section/div/main/nav/nav/button[3]').click()
            wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'li')))
            self.browser.find_element_by_tag_name('input').clear()
            self.browser.find_element_by_tag_name('input').send_keys(
                '365', Keys.ENTER)
            self.browser.find_element_by_xpath(
                '//*[@id="react-tabs-1"]/div/div/div[1]/div/div/div[1]/div[2]/div/div[1]/select/option[7]'
            ).click()
            wait.until(
                EC.visibility_of_element_located((
                    By.XPATH,
                    '//*[@id="react-tabs-1"]/div/div/div[1]/div/div/div[1]/div[3]/div[1]/div/div[2]/div'
                )))
            time.sleep(2)
            fullTitleIsPresent = self.browser.page_source.find(
                jobDetails) != -1
            halfTitleIsPresent = halfJobDetails in self.browser.page_source
            if not halfTitleIsPresent or not fullTitleIsPresent:
                time.sleep(1)
                self.browser.find_element_by_xpath(
                    '//*[@id="root"]/section/div/nav/a[1]').click()
                wait.until(
                    EC.invisibility_of_element(
                        (By.CLASS_NAME, 'sc-lcpuFF eOXROa')))
                if wait.until(
                        EC.element_to_be_clickable(
                            (By.CLASS_NAME, 'btn-add'))):
                    self.browser.find_elements_by_class_name(
                        'btn-add')[5].click()
                    # find the job description field and select
                    # jobDescriptionInput = self.browser.find_element_by_id(
                    #     'root_applications_0_details')
                    # jobDescriptionInput.click()
                    # jobDescriptionInput.send_keys(jobDescription)
                    #
                    title = self.browser.find_element_by_id(
                        'root_applications_0_jobTitle')
                    title.click()
                    title.send_keys(jobTitle)
                    actions = ActionChains(self.browser)
                    companyButton = self.browser.find_elements_by_class_name(
                        'css-1hwfws3')[0]
                    actions.click(companyButton)
                    actions.send_keys(jobCompany)
                    actions.pause(2)
                    # actions.send_keys(Keys.UP)
                    actions.send_keys(Keys.ENTER)
                    # actions.send_keys(Keys.TAB)
                    actions.perform()
                    actions.reset_actions()
                    #
                    # find the link
                    # find the source field and create or select
                    sourceButton = self.browser.find_elements_by_class_name(
                        'css-1hwfws3')[1]
                    actions = ActionChains(self.browser)
                    actions.reset_actions()
                    actions.click(sourceButton)
                    actions.send_keys(jobWebsite)
                    actions.pause(2)
                    actions.send_keys(Keys.ENTER)
                    actions.perform()
                    actions.reset_actions()
                    #
                self.browser.find_elements_by_tag_name('button')[9].click()
                wait.until(
                    EC.url_matches(
                        'https://www.interview-db.com/profile/job-search'))
                # time.sleep(10)
            else:
                skip_count += 1
                if skip_count > 40:
                    multiple_skips = True

            self.browser.get(
                'http://localhost:3000/cover-letter-generator/all-jobs/')
            all_jobs = self.browser.find_elements_by_tag_name('a')
            if halfTitleIsPresent or fullTitleIsPresent:
                print('Skipped Job #', i / 2, ' skip count is -', skip_count)
            else:
                print('Finished Job #', (i / 2))
            i += 2
Ejemplo n.º 17
0
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
import time as t


def findCss(driver, css):
    return driver.find_element_by_css_selector(css)


driver = webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('http://www.baidu.com')
action = ActionChains(driver)
action.move_to_element(
    driver.find_element_by_css_selector('#u1 > a.pf')).perform()
findCss(driver, '#wrapper > div.bdpfmenu > a.setpref').click()

#index方式每页显示50条
select = Select(driver.find_element_by_xpath('//*[@id="nr"]'))
select.select_by_index(2)
driver.find_element_by_xpath('//*[@id="nr"]').click()
t.sleep(3)

#文本的方式每页显示20条
select.select_by_visible_text(u'每页显示20条')
driver.find_element_by_xpath('//*[@id="nr"]').click()
t.sleep(3)
Ejemplo n.º 18
0
 def click_logout(self):
     el = WebDriverWait(self.driver, 30).until(
         EC.element_to_be_clickable(
             IoStoreLevel1NavigationMenuSection.Locators.LOGOUT_LINK))
     return ActionChains(self.driver).move_to_element(el).click().perform()
Ejemplo n.º 19
0
def close_dropdown():
    from selenium.webdriver.common.action_chains import ActionChains
    actions = ActionChains(driver)
    body = driver.find_element_by_css_selector("a.logo")
    actions.move_to_element(body).click().perform()
Ejemplo n.º 20
0
    else:
        N = 30
    for j in range(1, N + 1):
        if j < 10:
            tmpS = '0' + str(j)
        else:
            tmpS = str(j)
        dates.append(Stri + str(i) + tmpS)

driver = webdriver.Chrome()
driver.get("http://stockhtm.finance.qq.com/fund/jzzx/index.htm")
#assert "Python" in driver.title
elem = driver.find_element_by_name("textfield")

for dat in dates:
    #print dat
    elem.clear()
    elem.send_keys(dat)
    elem1 = driver.find_element_by_name("Submit01")
    action1 = ActionChains(driver).move_to_element(elem1)
    action1.click(elem1)
    action1.perform()
    elem2 = driver.find_element_by_name("Submit02")
    action2 = ActionChains(driver).move_to_element(elem2)
    action2.click(elem2)
    action2.perform()

#elem.send_keys(Keys.RETURN)
#print driver.page_source
#driver.get("http://stockhtm.finance.qq.com/fund/jzzx/index.htm")
Ejemplo n.º 21
0
# opening web.Whatsapp
web = webdriver.Firefox()
web.get('http://web.whatsapp.com')

# Scanning the QR Code
input('Enter anything after scanning QR code')
time.sleep(5)

# Finding Groups
for name in groups:
    user = web.find_element_by_xpath('//span[@title = "{}"]'.format(name))
    user.click()
    msg_box = web.find_element_by_class_name('_2S1VP')
    # sending messages
    for line in sell_list:
        msg_box.send_keys(line)
        ActionChains(web).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(
            Keys.ENTER).key_up(Keys.SHIFT).perform()

    button = web.find_element_by_class_name('_2lkdt')
    button.click()
    # Sleep random time
    time.sleep(random_time_sleep)

###     check

print("The following groups had been message:")
print(groups)
print("Message Sent:")
print(sell_list)
input("Hit enter/return or enter any key to quit")
Ejemplo n.º 22
0
    account_dict = {'username': account, 'password': pwd}
    ele_tupe = findElement(d, ele_dict)
    sendVals(ele_tupe, account_dict)


if __name__ == '__main__':
    try:
        login_test()
        d.save_screenshot('lodin.png')
        # 获取滑块
        slider = d.find_element_by_xpath(
            '//div[@id="gc-box"]/div/div[3]/div[2]')
        print(slider)
        # 鼠标悬停事件(显示完整图片)
        ActionChains(d).move_to_element(slider).perform()
        time.sleep(1)
        screenshot = d.save_screenshot('tu1.png')

        print(type(screenshot))

        time.sleep(2)

        # 鼠标点击(显示残缺图片)
        slider.click()
        time.sleep(3)
        d.save_screenshot('tu2.png')

        # 获取 图片的位置大小
        img1 = d.find_element_by_xpath(
            xpath='//div[@class="gt_cut_fullbg gt_show"]')
Ejemplo n.º 23
0
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://orteil.dashnet.org/cookieclicker/")
driver.implicitly_wait(10)

cookie = driver.find_element_by_id("bigCookie")
cookie_count = driver.find_element_by_id("cookies")
items = [
    driver.find_element_by_id("productPrice" + str(i))
    for i in range(1, -1, -1)
]

actions = ActionChains(driver)
actions.click(cookie)

for i in range(5000):
    actions.perform()
    count = int(cookie_count.text.split(" ")[0])
    for item in items:
        value = int(item.text)
        if value <= count:
            upgrade_actions = ActionChains(driver)
            upgrade_actions.move_to_element(item)
            upgrade_actions.click()
            upgrade_actions.perform()
Ejemplo n.º 24
0
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

br = webdriver.Chrome()

br.get("https://www.baidu.com")

first = br.find_element_by_link_text("设置")
ActionChains(br).move_to_element(first).perform()
menu = br.find_element_by_link_text("搜索设置")
menu.click()
Ejemplo n.º 25
0
def auto_data_preview(driver):
    wait = WebDriverWait(driver, 30)
    # 1. 起一个action实例
    actions = ActionChains(driver)
    # 2. 点击'数据预览'
    wait.until(EC.visibility_of_element_located((By.LINK_TEXT, '数据预览')))
    data_presee = driver.find_element_by_link_text('数据预览')
    actions.move_to_element(data_presee).perform()
    wait_for(2)
    data_presee.click()
    wait_for(2)
    # 3. 输入'csv文件路径'和'读入行数' 并点击提交
    wait.until(EC.visibility_of_element_located((By.ID, 'file_list')))
    wait.until(EC.visibility_of_element_located((By.ID, 'nrows_list')))
    wait.until(
        EC.visibility_of_element_located((By.XPATH, '//*[@id="csv-sumbit"]')))
    file_list = driver.find_element_by_id('file_list')
    nrows_list = driver.find_element_by_id('nrows_list')
    csv_submit = driver.find_element_by_xpath('//*[@id="csv-sumbit"]')
    file_list.clear()
    wait_for(1)
    file_list.send_keys('heart.csv')
    wait_for(1)
    nrows_list.clear()
    wait_for(1)
    nrows_list.send_keys('1000')
    wait_for(1)
    csv_submit.click()
    wait_for(2)
    # 4. 点开df_heart 并展现读入的数据 再关闭
    wait.until(
        EC.visibility_of_element_located(
            (By.XPATH, '//*[@id="accordion"]/div/div[1]/a')))
    df_heart_view = driver.find_element_by_xpath(
        '//*[@id="accordion"]/div/div[1]/a')
    actions = ActionChains(driver)
    actions.move_to_element(df_heart_view).perform()
    wait_for(1)
    df_heart_view.click()
    wait_for(2)
    touch_actions = TouchActions(driver)
    touch_actions.scroll_from_element(df_heart_view, 0, 400).perform()
    wait_for(2)
    df_heart_view.click()
    wait_for(2)
    # 5. 展示已经读入HDFStore的文件
    wait.until(
        EC.visibility_of_element_located((By.XPATH, '//*[@id="df_sumbit"]')))
    wait.until(
        EC.visibility_of_element_located((By.XPATH, '//*[@id="store_path"]')))
    df_submit = driver.find_element_by_xpath('//*[@id="df_sumbit"]')
    store_path = driver.find_element_by_xpath('//*[@id="store_path"]')
    store_path.clear()
    wait_for(1)
    store_path.send_keys('data_curation.h5')
    wait_for(1)
    df_submit.click()
    wait_for(1)
    wait.until(
        EC.visibility_of_element_located(
            (By.XPATH, '//*[@id="accordion"]/div/div[1]/a')))
    df_show = driver.find_element_by_xpath('//*[@id="accordion"]/div/div[1]/a')
    df_show.click()
    wait_for(1)
    touch_actions = TouchActions(driver)
    touch_actions.scroll_from_element(df_show, 0, 800).perform()
    wait_for(1)
    df_show.click()
    wait_for(2)
def scraper_outdoor(request):

    # headers in csv file

    try:
        if path.exists("outdoor.csv"):
            os.remove("outdoor.csv")
    finally:
        c = 0
    headers = [
        'name', 'ref', 'price', 'special price', 'home delivery in stock',
        'description', 'Walsall quantity', 'Walsall in stock text',
        'Wolverhampton quantity', 'Wolverhampton in stock text',
        'Oldbury quantity', 'Oldbury in stock text', 'Castlevale quantity',
        'Castlevale in stock text', 'image1', 'image2', 'image3', 'image4',
        'image5'
    ]
    with open('outdoor.csv', 'a', newline='') as f_object:
        writer_object = csv.writer(f_object)
        writer_object.writerow(headers)
        f_object.close()
    item = []
    browser.get("https://www.smythstoys.com/uk/en-gb/outdoor/c/SM0603")
    pickle.dump(browser.get_cookies(), open("cookies.pkl", "wb"))
    print('Scraper is runing now....')

    # Dismiss cookie dialog

    sleep(10)
    try:
        cookie_button = WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "cookieProcessed")))
        ActionChains(browser).move_to_element(cookie_button).click(
            cookie_button).perform()
        sleep(3)
    finally:
        sleep(3)

    scrap_data = []
    product_links = []

    # Get item number

    sleep(2)
    array_string_item = browser.find_element_by_xpath(
        "/html/body/div[7]/div[1]/div[2]/div[3]/div/div[1]/div[1]/div[1]/div[2]/div/div[1]/h4"
    ).get_attribute('textContent').strip().split(' ')[0]
    number_of_items = array_string_item.replace(',', '')

    # Send load more button click event

    for i in range(int(int(number_of_items) / 60)):
        load_more_button = WebDriverWait(browser, 60).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "productsLoadMore")))
        ActionChains(browser).move_to_element(load_more_button).click(
            load_more_button).perform()
        sleep(3)
        print("click %d times" % i)
    print("Load more finished...")

    main_div = browser.find_element_by_xpath(
        "/html/body/div[7]/div[1]/div[2]/div[3]/div/div[1]/div[2]/div")

    # Get href links
    hrefs = main_div.find_elements_by_class_name("trackProduct")
    for i in range(int(len(hrefs) / 2)):
        if i % 10 == 0:
            print("%d hrefs added" % i)
        product_links.append(hrefs[i * 2].get_attribute('href'))
    print("%d hrefs finished..." % len(product_links))

    # Loop product links

    for product_link in product_links:
        browser.get(product_link)
        sleep(4)
        name = None
        while not name:
            try:
                name = browser.find_element_by_xpath(
                    "/html/body/div[7]/section/div/div/div[2]/div[1]/h1")
            except (NoSuchElementException, NameError) as e:
                time.sleep(2)
        name = name.text.strip()
        images = browser.find_elements_by_xpath(
            "/html/body/div[7]/section/div/div/div[1]/div/div[1]/div/div[1]/div//img[@class='responsive-image']"
        )
        image_src = ['', '', '', '', '']
        for i in range(5):
            if i < len(images):
                image_src[i] = images[i].get_attribute("src")
            else:
                image_src[i] = ""
        ref_number = browser.find_element_by_xpath(
            "/html/body/div[7]/section/div/div/div[2]/div[1]/div[1]/div/div[2]/div"
        ).text.strip()[4:]
        prices = browser.find_element_by_class_name(
            "price_tag").find_elements_by_class_name("notranslate")
        if len(prices) == 1:
            normal_price = prices[0].text.strip()[1:]
            discount_price = ""
        else:
            normal_price = prices[1].text.strip()[1:]
            discount_price = prices[0].text.strip()[1:]
        home_delivery = browser.find_elements_by_class_name(u"homeDelivery")
        if len(home_delivery) != 0:
            in_stock = home_delivery[0].text.strip()
        else:
            in_stock = ""
        description = ""
        description_lis = None
        description_lis = browser.find_element_by_xpath(
            u'//*[@id="profile"]/div/div[1]/ul')
        if description_lis != None:
            description_lis = description_lis.find_elements_by_class_name(
                "font-regular")
            for description_li in description_lis:
                description = description + description_li.text.strip(
                ) + "<br/>"
        else:
            description_lis = browser.find_element_by_xpath(
                u'//*[@id="profile"]').findElements(By.tagName('p'))
            for description_li in description_lis:
                description = description + description_li.text.strip(
                ) + "<br/>"
        # category = browser.find_elements_by_class_name(u"breadcrumb-text")[1].text

        # Open Store Dialog
        change_store_button = browser.find_elements_by_class_name(
            "js-pickup-in-store-button")
        if len(change_store_button) != 0:
            ActionChains(browser).move_to_element(
                change_store_button[0]).click(
                    change_store_button[0]).perform()
            sleep(4)

            # Get City Stock
            try:
                WebDriverWait(browser, 10).until(
                    EC.element_to_be_clickable(
                        (By.CLASS_NAME, "js-pickup-in-store-button")))
            finally:
                c = 0
            Walsall_text = None
            while not Walsall_text:
                try:
                    Walsall_text = browser.find_elements_by_class_name(
                        "resultStock")[57].text.strip()
                except IndexError:
                    browser.get(product_link)
                    sleep(4)
                    change_store_button = browser.find_elements_by_class_name(
                        "js-pickup-in-store-button")
                    ActionChains(browser).move_to_element(
                        change_store_button[0]).click(
                            change_store_button[0]).perform()
                    sleep(4)
            Walsall_text = Walsall_text[57].text.strip()
            if "Out of stock" in Walsall_text:
                Walsall_stock = "Out of stock"
                Walsall_quantity = ""
            else:
                Walsall_stock = "In stock"
                Walsall_quantity = Walsall_text[:-8]

            Wolverhampton_text = browser.find_elements_by_class_name(
                "resultStock")[56].text.strip()
            if "Out of stock" in Wolverhampton_text:
                Wolverhampton_stock = "Out of stock"
                Wolverhampton_quantity = ""
            else:
                Wolverhampton_stock = "In stock"
                Wolverhampton_quantity = Walsall_text[:-8]

            Oldbury_text = browser.find_elements_by_class_name(
                "resultStock")[59].text.strip()
            if "Out of stock" in Oldbury_text:
                Oldbury_stock = "Out of stock"
                Oldbury_quantity = ""
            else:
                Oldbury_stock = "In stock"
                Oldbury_quantity = Walsall_text[:-8]

            Castlevale_text = browser.find_elements_by_class_name(
                "resultStock")[61].text.strip()
            if "Out of stock" in Castlevale_text:
                Castlevale_stock = "Out of stock"
                Castlevale_quantity = ""
            else:
                Castlevale_stock = "In stock"
                Castlevale_quantity = Walsall_text[:-8]
        else:
            Walsall_stock = ""
            Walsall_quantity = ""
            Wolverhampton_stock = ""
            Wolverhampton_quantity = ""
            Oldbury_stock = ""
            Oldbury_quantity = ""
            Castlevale_stock = ""
            Castlevale_quantity = ""

        # Save Data
        scrap_data = [
            name, ref_number, normal_price, discount_price, in_stock,
            description, Walsall_quantity, Walsall_stock,
            Wolverhampton_quantity, Wolverhampton_stock, Oldbury_quantity,
            Oldbury_stock, Castlevale_quantity, Castlevale_stock, image_src[0],
            image_src[1], image_src[2], image_src[3], image_src[4]
        ]
        save_outdoor(scrap_data)

    return HttpResponse('Scraping finished...')
Ejemplo n.º 27
0
        cities = pd.concat([cities, extractCites(driver,
                                                 regionsDF.loc[region]["Регион"])],
                            ignore_index=True)
        logger.info(f'Города в регионе:\n {cities[cities["Регион"]==regionsDF.loc[region]["Регион"]]}')
        regionsMenuClose(driver)

        # Перебираем все города в регионе и для каждого смотрим тарифы
        for i in range(len(cities[cities["Регион"] == regionsDF.loc[region]["Регион"]])):

            regionsMenuOpen(driver)
            regionsMenuClick(driver, regionsDF.loc[region]["Регион"],
                             regionsDF.loc[region]['class'])

            citesWebDriver = driver.find_elements(By.CLASS_NAME,
                                                  "mts16-popup-regions__link")
            for j in citesWebDriver:
                city = cities[cities["Регион"] == regionsDF["Регион"].loc[region]]["Город"].values[i]
                if j.get_attribute("innerText") == city:
                    logger.info(f'Изучаем город: {city}')
                    ActionChains(driver).move_to_element(j).click(j).perform()
                    break

            showMoreClick(driver)
            t = tarifs(driver, city, regionsDF.loc[region]["Регион"])
            logger.info(f'Для города {city} обнаружено {len(t)} тарифов')
            df = pd.concat([df, t])
finally:
    df.reset_index()
    df.to_excel("tarifs1.xlsx")
    driver.close()
def sendMessage():
    actions = ActionChains(web)
    for i in range(0, noOfTimes):
        actions.send_keys(msg)
        actions.send_keys(Keys.RETURN)
    actions.perform()
Ejemplo n.º 29
0
driver.find_element_by_xpath(
    '/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[1]/div[2]/input'
).clear()
driver.find_element_by_xpath(
    '/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[1]/div[2]/input'
).send_keys('17600117243')
driver.find_element_by_xpath(
    '/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[2]/input'
).clear()
driver.find_element_by_xpath(
    '/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[2]/input'
).send_keys('117243')
driver.find_element_by_xpath(
    '/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[2]/input'
).submit()
#driver.find_element_by_xpath('/html/body/div[1]/div/section/div[2]/ul[2]/li[1]/form/div[4]/input').click()
#time.sleep(5)
#driver.refresh()
'''
driver.get('https://litao.yunke.com/org.main.template#bottom')
test = driver.find_element_by_xpath('//*[@id="template-course-data"]/div/form/div[3]/div/span[2]/a')
test.click()
element = driver.find_element_by_xpath('//*[@id="template-course-data"]/div/form/div[3]/dl/dd[10]/div/img')
target = driver.find_element_by_xpath('//*[@id="template-course-data"]/div/form/div[3]/dl/dd[1]/div/img')
ActionChains(driver).drag_and_drop(element,target).perform()
'''
#WebDriverWait(driver,1,0.5).until(expected_conditions.presence_of_all_elements_located((By.ID,'chick-down-show')))
above = driver.find_element_by_id('chick-down-show')
ActionChains(driver).move_to_element(above).perform()
#driver.quit()
Ejemplo n.º 30
0
from  selenium import  webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep

driver=webdriver.Firefox()
driver.get("http://www.baidu.com")
driver.maximize_window()

driver.find_element_by_css_selector("#kw").send_keys("Python")
element=driver.find_element_by_css_selector("#kw")
sleep(3)

#双击操作
ActionChains(driver).double_click(element).perform()
sleep(2)

#右击操作
ActionChains(driver).context_click(element).perform()
sleep(2)

#鼠标悬停
above=driver.find_element_by_css_selector(".pf")
ActionChains(driver).move_to_element(above).perform()
sleep(3)
driver.quit()