Example #1
0
def getcurrent(driver0, orderid):
    while True:
        try:
            time.sleep(2)
            bMutex.lock()
            wait.WebDriverWait(driver0, 5).until(
                EC.presence_of_element_located((By.ID, 'search-text-box')))
            idinput = driver0.find_element_by_id("search-text-box")
            searchbutton = driver0.find_element_by_name("Search")
            driver0.execute_script("arguments[0].value=" + "'" + orderid + "'",
                                   idinput)
            driver0.execute_script('arguments[0].click();', searchbutton)
            # 只有不出现任何问题,才能继续,否则重新来一遍
            bMutex.unlock()
            break
        except Exception as e:
            bMutex.unlock()
            traceback.print_exc()
            print('try again--------------------')

    try:
        # 等5秒,如果还没搜出来结果,那么肯定就是没有了,返回None
        time.sleep(2)
        bMutex.lock()
        idDom = wait.WebDriverWait(driver0, 3).until(
            EC.presence_of_element_located((By.ID, 'currentThreadSenderId')))
        current = idDom.get_attribute('value')
        bMutex.unlock()
        return current
    except Exception as e:
        bMutex.unlock()
        print('No result found, ready to send message')
        return None
def push_to_listserv(emails_file):

    profile = webdriver.FirefoxProfile()
    profile.accept_untrusted_certs = True
    profile.assume_untrusted_cert_issuer = True
    capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
    capabilities['acceptInsecureCerts'] = True
    browser = webdriver.Firefox(firefox_profile=profile,
                                capabilities=capabilities)
    try:
        _create_unverified_https_context = ssl._create_unverified_context
    except AttributeError:
        # Legacy Python that doesn't verify HTTPS certificates by default
        pass
    else:
        # Handle target environment that doesn't support HTTPS verification
        ssl._create_default_https_context = _create_unverified_https_context

    # Open login page and wait till it loads
    browser.get(settings.LISTSERV_FORM_ADDRESS)
    wait.WebDriverWait(browser, 10).until(
        expected_conditions.element_to_be_clickable(
            (By.XPATH, "//form/p/input[1]")))

    # Submit login info
    email_field = browser.find_element_by_id("Email Address")
    email_field.clear()
    email_field.send_keys(settings.LISTSERV_USERNAME)
    password_field = browser.find_element_by_id("Password")
    password_field.clear()
    password_field.send_keys(settings.LISTSERV_PASSWORD)
    email_field.submit()

    # Wait for login request to complete
    wait.WebDriverWait(browser, 10).until(
        expected_conditions.element_to_be_clickable((By.ID, "Input File")))

    # Open the email upload page and submit the form
    replace_all_button = browser.find_element_by_id("radiob")
    replace_all_button.click()
    file_upload = browser.find_element_by_id("Input File")

    file_upload.send_keys(emails_file)

    print("Waiting for file upload...")
    time.sleep(LOAD_WAIT_SECS)

    file_upload.submit()

    # TODO: parse response and notify someone
    print("Waiting for listserv to process...")
    time.sleep(LOAD_WAIT_SECS)

    print('pause')
    change_message = browser.find_element_by_class_name('message').text

    return change_message
Example #3
0
 def _create_order(self):
     """
     创建订单
     """
     time.sleep(0.5)
     passenger_list = browser.find_els_if_exist('#normal_passenger_id > li')
     # 选择乘坐人
     passenger_index = 1
     self._ticket_info['passengers'] = []
     for passenger in config.passengers:
         for passenger_li in passenger_list:
             passenger_input = passenger_li.find_element_by_tag_name(
                 'input')
             if passenger_li.find_element_by_tag_name(
                     'label').text == passenger:
                 console.print(f"选择乘坐人 [{passenger}] . . .")
                 self._ticket_info['passengers'].append(passenger)
                 passenger_input.click()
                 warning_alert = browser.find_el_if_exist(
                     'content_defaultwarningAlert_id', by=By.ID)
                 if warning_alert:
                     warning_alert.find_element_by_id(
                         'qd_closeDefaultWarningWindowDialog_id').click()
                     time.sleep(0.5)
                 # 选择席座
                 console.print(
                     f"开始选择席座 [{self._ticket_info['seat_type']}] . . .")
                 seat_select = browser.find_element_by_id(
                     f"seatType_{str(passenger_index)}")
                 _, seat_type_value = _get_seat_type_index_value(
                     self._ticket_info['seat_type'])
                 if seat_type_value != 0:
                     Select(seat_select).select_by_value(
                         str(seat_type_value))
                 passenger_index += 1
                 time.sleep(0.5)
     if passenger_index == 1:
         console.print("未找到乘客信息 ... 提交订单失败", style="bold red")
     print('正在提交订单 . . .')
     wait.WebDriverWait(browser, 5).until(
         ec.element_to_be_clickable((By.ID, 'submitOrder_id'))).click()
     print('正在确认订单 . . .')
     wait.WebDriverWait(browser, 5).until(
         ec.element_to_be_clickable((By.ID, 'qr_submit_id'))).click()
     # 截取屏幕,订单信息页
     print('预订成功,正在截取屏幕 . . .')
     time.sleep(5)
     browser.screenshot(
         f'{self.fs}_{self.ts}_{config.from_time.replace("-", "")}_{self._ticket_info["train"].lower()}.png'
     )
     time.sleep(60)
Example #4
0
def scrap_page(url, filename):
    """
    Download all the text from a particular page on MqDq. Also attempt to scan the page
    :param url:
    :param filename:
    :return:
    """
    driver.get(url)
    scansionIdLocation = "//input[@name='idScansione' and @type='hidden']"
    livelloIdLocation = "//input[@name='livello' and @type='hidden']"
    try:
        wait.WebDriverWait(
            driver, 300).until(lambda x: element_exists(scansionIdLocation))
        scansionId = driver.find_element_by_xpath(
            scansionIdLocation).get_attribute('value')
        scansionId += "," + driver.find_element_by_xpath(
            livelloIdLocation).get_attribute('value')
    except:
        print("Waiting for page timeout for\t" + url + "\t" + filename)
        scansionId = "0"
    buttonLocation = "//button[@class='btn btn-primary' and @title='' and " \
                     "@onclick='eseguiScansione("+scansionId+")']"
    appearAfterScansion = [
        "//div[@class='pedecerto']", "//table[@class='versoScandito']"
    ]
    try:
        driver.find_element_by_xpath(buttonLocation).click()
        wait.WebDriverWait(driver, 1200).until(lambda x: sum(
            [element_exists(y) for y in appearAfterScansion]) != 0)

    except TimeoutException:
        print("Waiting for scansion timeout for\t" + url + "\t" + filename)
    except urllib3.exceptions.MaxRetryError:
        sleep(1800)
    except:
        pass

    try:
        html = driver.page_source
    except urllib3.exceptions.MaxRetryError:
        sleep(1800)
    parser = PageParser()
    data = parser.feed(html)

    with open(filename, "w") as file:
        file.writelines(data["text"])
    if len(data["scansions"]) > 0:
        with open(filename + ".scanned", "w") as file:
            file.writelines(data["scansions"])
Example #5
0
    def check(self, start_end, check, trains):
        # 调用余票查询模块
        browser.get(self.ticket_url)
        self.num = check.get_info(start_end, 1, trains)
        button_alart = wait.WebDriverWait(browser, 3).until(
            EC.element_to_be_clickable(
                (By.ID, 'gb_closeDefaultWarningWindowDialog_id')))
        button_alart.click()

        button = wait.WebDriverWait(browser, 3).until(
            EC.element_to_be_clickable((By.ID, 'query_ticket')))
        button.click()
        if self.purpose == '学生':
            browser.find_element_by_id('sf2').click()
            button.click()
Example #6
0
def getlist(driver0):
    allorderlist = []
    alldatetimelist = []
    while True:
        time.sleep(2)
        orderlisthtml = wait.WebDriverWait(driver0, 10000000).until(
            EC.presence_of_element_located((By.ID, 'myo-table')))

        # 匹配
        pattern = re.compile(r'\d*-\d*-\d*')
        orderlist = re.findall(pattern, orderlisthtml.text)
        print(orderlist)
        allorderlist.extend(orderlist)

        pattern1 = re.compile(r'\w{3} \d, \d{4}')
        datelist = re.findall(pattern1, orderlisthtml.text)

        pattern2 = re.compile(r'\d+:\d+:\d+ \w\w')
        timelist = re.findall(pattern2, orderlisthtml.text)

        for i, j in zip(datelist, timelist):
            thisdatetime = datetime.strptime(i + ' ' + j, "%b %d, %Y %I:%M:%S %p")
            alldatetimelist.append(thisdatetime)
        # 翻页
        try:
            nextpagebutton = driver0.find_element_by_xpath("//a[text()='Next' and @class = 'myo_list_orders_link']")
            nextpagebutton.click()
            print("next")
        except Exception:
            print("finish")
            break
    print("``````````````")
    print(alldatetimelist)
    return allorderlist, alldatetimelist
 def click_rich_text(self):
     el = self.find_element_by_css_selector('div.rte-control')
     self._tester.assertEqual('Rich Text', el.text)
     el.click()
     wait.WebDriverWait(self._tester.driver, 15).until(
         ec.element_to_be_clickable((by.By.ID, AddLesson.RTE_EDITOR_ID)))
     return self
Example #8
0
def getorderinfo3(driver0, orderid):
    bMutex.lock()
    js = 'window.open(\"https://sellercentral.amazon.com/gp/orders-v2/details?orderID=' + orderid + '\");'
    handle = driver0.current_window_handle
    driver0.execute_script(js)

    handles = driver0.window_handles
    for newhandle in handles:

        # 筛选新打开的窗口B

        if newhandle != handle:
            # 切换到新打开的窗口B

            driver0.switch_to_window(newhandle)

    # 在新打开的窗口B中操作
    wait.WebDriverWait(driver0, 10000000).until(
        EC.presence_of_element_located(
            (By.ID, 'myo-order-details-item-product-details')))
    o1 = driver0.find_element_by_xpath(
        "//a[contains(@href,'https://www.amazon.com/gp/product/')]").text

    # 关闭当前窗口B

    driver0.close()

    # 切换回窗口A

    driver0.switch_to_window(handle)
    bMutex.unlock()
    return o1
Example #9
0
def getorderinfo(driver0,orderid):
    orderrow = driver.find_element_by_id("row-"+orderid)
    orderinfo = orderrow.find_element_by_xpath("//span[contains(@id,'___product')]")
    o1 = orderinfo.text
    if(str(orderinfo.text)[-3:] == '...'):
        info_a = orderrow.find_element_by_link_text(orderid)
        js = 'window.open(\"' + info_a.get_attribute('href') + '\");'
        handle = driver0.current_window_handle
        driver0.execute_script(js)

        handles = driver0.window_handles
        for newhandle in handles:

            # 筛选新打开的窗口B

            if newhandle != handle:

        # 切换到新打开的窗口B

                driver0.switch_to_window(newhandle)

        # 在新打开的窗口B中操作
        wait.WebDriverWait(driver0, 10000000).until(
            EC.presence_of_element_located((By.ID, 'myo-order-details-item-product-details')))
        o1 = driver0.find_element_by_xpath("//a[contains(@href,'https://www.amazon.com/gp/product/')]").text

        # 关闭当前窗口B

        driver0.close()

        # 切换回窗口A

        driver0.switch_to_window(handles[0])

    return o1
Example #10
0
 def _get_target(self):
     """Get target"""
     element = wait.WebDriverWait(self._driver, 10).until(
         expected_conditions.presence_of_element_located(
             (by.By.ID, 'rightLabelValueContainer')
         )
     )
     children = element.find_elements_by_tag_name('div')
     balance = None
     date = None
     for child in children:
         item_children = child.find_elements_by_tag_name('div')
         found_balance = False
         found_date = False
         for item in item_children:
             if not found_balance and item.text == 'Last Statement Balance:':
                 found_balance = True
             elif found_balance:
                 balance = item.text
             elif not found_date and item.text == 'Payment Due Date:':
                 found_date = True
             elif found_date:
                 date = item.text
             elif found_date and found_balance:
                 break
     self._balance = 'citi: ' + balance
     splitted_date = date.split('/')
     self._date = datetime.datetime(int(splitted_date[2]), int(splitted_date[0]), int(splitted_date[1]))
Example #11
0
def iframe_wait(driver, timeout=30):
    waiter = wait.WebDriverWait(driver, timeout)
    IFRAME_XPATH = '//iframe'
    time.sleep(0.5)
    frame = cycle_wait(driver, IFRAME_XPATH, lambda e: len(e) > 0)
    driver.switch_to.default_content()
    driver.switch_to.frame(driver.find_element_by_xpath(IFRAME_XPATH))
Example #12
0
 def shading_disappearing_in_frame(self) -> None:
     # TODO: Пока не реализовано!!!
     """ Ожидание пропадания затемнения во фрейме """
     self.log.debug(f"Work '{self.get_method_name()}'")
     shading_xpath = "//div[@id='BlockLoaderPanel' and contains(@style, 'display')]"
     wait.WebDriverWait(self.drv, config_file.IMPLICITLY_WAIT_TIMEOUT) \
         .until(ec.invisibility_of_element_located((By.XPATH, shading_xpath)))
Example #13
0
 def _enter_card_detail(self):
     """Enter card detail"""
     element = wait.WebDriverWait(self._driver, 10).until(
         expected_conditions.presence_of_all_elements_located(
             (by.By.ID, 'cmlink_AccountNameLink')
         )
     )
     element[0].click()
Example #14
0
def _init():
    # 现在使用这个url地址
    browser.get(login_page)
    # 等待用户密码登录按钮可以点击,切换到用户密码登录 Tab
    wait.WebDriverWait(browser, 5).until(
        ec.element_to_be_clickable(
            (By.CLASS_NAME, 'login-hd-account'))).click()
    time.sleep(1)
Example #15
0
 def test(self):
     driver = webtest.new_webdriver_session()
     url = "http://localhost:%s%s" % (self.port, web_path)
     driver.get(url)
     wait.WebDriverWait(driver, 10).until(
         expected_conditions.title_contains("test"))
     title = driver.title
     if "failing test" in title or "passing test" not in title:
         self.fail(title)
Example #16
0
 def _wait_till_text_present_in_element(self, locator, text):
     condition = expected_conditions.text_to_be_present_in_element(locator,
                                                                   text)
     try:
         wait.WebDriverWait(self.driver, self.explicit_wait).\
             until(condition)
     except Exceptions.TimeoutException:
         return False
     return True
Example #17
0
 def _wait_until(self, predicate, timeout=None, poll_frequency=0.5):
     """Wait until the value returned by predicate is not False or
     the timeout is elapsed.
     'predicate' takes the driver as argument.
     """
     if not timeout:
         timeout = self.explicit_wait
     wait.WebDriverWait(self.driver, timeout,
                        poll_frequency).until(predicate)
def xpath_await_find(driver, xpath: str, waiting_time: int = WAITING_TIME):
    """Ищет и возвращает элемент с заданным xpath

    При необходимости предварительно ждет загрузки в течении определенного количества секунд
    """
    load_wait = wait.WebDriverWait(driver, waiting_time)
    element_wait = expected_conditions.presence_of_element_located((By.XPATH, xpath))
    element = load_wait.until(element_wait)
    return element
Example #19
0
 def _wait_until_not(self, condition, timeout: TimeoutType = DEFAULT_TIMEOUT):
     """Wrapper method around Selenium WebDriverWait() with until_not().
     :param condition: Selenium expected_conditions
     :param timeout: int
     :return: boolean
     """
     if not timeout:
         timeout = 0
     return wait.WebDriverWait(self._webdriver, timeout).until_not(condition)
    def click_upload_and_expect_saved(self):
        self.find_element_by_link_text('Upload').click()
        self.expect_status_message_to_be('Saved.')

        # Page automatically redirects after successful save.
        wait.WebDriverWait(self._tester.driver,
                           15).until(ec.title_contains('Assets'))

        return AssetsPage(self._tester)
Example #21
0
def create_waiter(driver, action, timeout=10):
    waiter = wait.WebDriverWait(driver, timeout)

    def wait_and_make_action(selector):
        waiter.until(EC.presence_of_element_located((By.XPATH, selector)))
        if action is None:
            return
        action(driver.find_element_by_xpath(selector))

    return wait_and_make_action
Example #22
0
 def login_success(self):
     try:
         return bool(
             wait.WebDriverWait (self.browser, 5).until (
                 EC.presence_of_element_located(
                     (By.XPATH,'//span[@target="_blank"]')
                 )
             )
         )
     except TimeoutException:
         return False
    def __init__(self, tester):
        super(EditorPageObject, self).__init__(tester)

        def successful_butter_bar(driver):
            butter_bar_message = driver.find_element_by_id(
                'gcb-butterbar-message')
            return 'Success.' in butter_bar_message.text or (
                not butter_bar_message.is_displayed())

        wait.WebDriverWait(self._tester.driver,
                           15).until(successful_butter_bar)
Example #24
0
 def login(self):
     browser.get(self.login_url)
     # 通过url的转变,判断是否登录成功
     wait.WebDriverWait(browser,
                        10000).until(EC.url_to_be(self.personal_url))
     print('登录成功')
     if browser.current_url == self.personal_url:
         start_end, check = self.add_cookie()
         self.check(start_end, check, trains=self.trains)
     else:
         print('登录失败')
Example #25
0
    def shading_disappearing(self) -> None:
        """ Ожидание исчезновения затемнения """
        self.log.debug(f"Work '{self.get_method_name()}'")
        rent_button_xpath = "//a[contains(@title,'Аренда, безвозмездное пользование, доверительное управление " \
                            "имуществом, иные договоры, предусматривающие передачу прав владения и пользования в " \
                            "отношении государственного и муниципального имущества')]"

        wait.WebDriverWait(self.drv, config_file.IMPLICITLY_WAIT_TIMEOUT) \
            .until(ec.element_to_be_clickable((By.XPATH, rent_button_xpath)))

        self.log.debug("The shading was gone")
Example #26
0
 def verify_no_image_file_by_name(self, name):
     wait.WebDriverWait(self._tester.driver, 5.0, 1.0).until(
         ec.visibility_of_element_located(
             (by.By.XPATH, '//h3[starts-with(.,\'Images & Documents\')]')))
     try:
         self.find_element_by_link_text(
             name)  # throw exception if not found
         raise AssertionError('Found file %s which should be absent' % name)
     except exceptions.NoSuchElementException:
         pass
     return self
Example #27
0
def _wait_for_condition(self, condition=None, timeout=None, poll_frequency=0.5, ignored_exceptions=None):
    """Wait for given javascript condition."""
    condition = functools.partial(condition or self.visit_condition, self)

    timeout = timeout or self.wait_time

    return wait.WebDriverWait(
        self.driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=ignored_exceptions
    ).until(
        lambda browser: condition()
    )
Example #28
0
 def wait(self, until, timeout: int = 30, interval: float or int = 0.5):
     """
     显示的等待页面加载并检查页面元素
     :param until:
     :param timeout:
     :param interval:
     :return:
     """
     return wait.WebDriverWait(self.driver,
                               timeout=timeout,
                               poll_frequency=interval).until(until)
Example #29
0
def payment_process():
    driver = webdriver.Edge(
        executable_path=
        'C:\\Users\\Pende\\Documents\\edge_driver\\msedgedriver.exe')
    driver.get('https://nawoka.fr/')

    # capabilities = desired_capabilities.DesiredCapabilities.CHROME.copy()
    # capabilities['platform'] = 'WINDOWS'
    # capabilities['version'] = '10'

    wait.WebDriverWait(driver, 3000).until(
        ec.element_to_be_clickable(
            (By.XPATH, '/html/body/main/div[2]/div[1]/a')))
    link_to_tops = driver.find_element_by_xpath(
        '/html/body/main/div[2]/div[1]/a')
    link_to_tops.click()

    wait.WebDriverWait(driver, 5000).until(
        ec.element_to_be_clickable(
            (By.XPATH, '/html/body/main/div/section/div[2]/div[3]/a')))
    link_to_products = driver.find_element_by_xpath(
        '/html/body/main/div/section/div[2]/div[3]/a')
    link_to_products.click()

    product_link = driver.find_element_by_xpath(
        '/html/body/main/div/div/section/div/div[2]/div/div[2]/a')
    product_link.click()

    add_to_cart = driver.find_element_by_xpath('//*[@id="btn_add_to_cart"]')
    add_to_cart.click()

    time.sleep(3)

    driver.execute_script(
        'window.location.href="https://nawoka.fr/shop/cart";')

    continue_to_shipment = driver.find_element_by_xpath(
        '/html/body/main/div/div[2]/div/div/div/a')
    continue_to_shipment.click()

    return driver
Example #30
0
def _init():
    # 跳转到登录页
    browser.get(login_page)
    time.sleep(1)
    if browser.find_el_if_exist('ERROR', by=By.ID) is not None:
        console.print('[red]12306请求过于频繁,请稍等重试 . . . [/red]')
        browser.wait_unblock()
    # 等待用户密码登录按钮可以点击,切换到用户密码登录 Tab
    wait.WebDriverWait(browser, 5).until(
        ec.element_to_be_clickable(
            (By.CLASS_NAME, 'login-hd-account'))).click()
    time.sleep(1)