Exemplo n.º 1
0
 def test_pay_with_yandex_kassa(self):
     success_page_domain = self.YA_KASSA_INNER_DOMAIN
     self.fill_contacts_data()
     self.select_payment_type('AC')
     self.submit_form()
     self.wait.until(EC.url_contains(success_page_domain))
     self.assertIn(success_page_domain, self.browser.current_url)
Exemplo n.º 2
0
    def test_one_click_buy_order_email(self):
        product_vendor_code = self.product.vendor_code

        increase_quantity = self.browser.find_element_by_xpath(
            '//*[@class="product-price-wrapper"]/div[1]/div[1]/span[3]/button[1]'
        )
        increase_quantity.click()
        increase_quantity.click()
        result_quantity = int(
            self.browser.find_element_by_class_name('js-touchspin')
            .get_attribute('value')
        )
        self.browser.execute_script('$("#input-one-click-phone").val("");')
        phone_field = self.browser.find_element_by_id('input-one-click-phone')
        phone_field.send_keys('2222222222')
        self.one_click.click()
        self.wait.until(EC.url_contains(self.success_order))

        sent_mail_body = mail.outbox[0].body
        self.assertIn('+7 (222) 222 22 22', sent_mail_body)
        self.assertInHTML(
            '<td align="left"'
            'style="border-bottom:1px solid #E4E4E4;padding:10px">{0}</td>'
            .format(product_vendor_code),
            sent_mail_body
        )
        self.assertIn(self.product.url, sent_mail_body)
        self.assertIn('{0} шт.'.format(result_quantity), sent_mail_body)
        self.assertInHTML(
            '<td align="right" style="padding:5px 10px">{0} руб.</td>'
            .format(int(self.product.price * result_quantity)),
            sent_mail_body
        )
Exemplo n.º 3
0
    def test_one_click_buy_action(self):
        """We can order product via one-click buy button."""
        self.browser.find_element_by_id(
            'input-one-click-phone').send_keys('2222222222')
        self.one_click.click()
        self.wait.until(EC.url_contains(self.success_order))

        self.assertIn(self.success_order, self.browser.current_url)
Exemplo n.º 4
0
    def test_autocomplete_item_link(self):
        """First autocomplete item should link on category page by click."""
        self.fill_input()
        self.click((By.CSS_SELECTOR, '.autocomplete-suggestions :first-child'))
        with self.screen_fail('test_autocomplete_item_link'):
            self.wait.until(EC.url_contains('/catalog/categories/'))

        self.assertTrue('/catalog/categories/' in self.browser.current_url)
Exemplo n.º 5
0
 def check_admin_table_for_items(self, user, cls_name, present=None, absent=None):
     admin_url = reverse('admin:{}_{}_changelist'.format(cls_name._meta.app_label, cls_name._meta.model_name))
     self.quick_backend_login(user, admin_url)
     self.wait.until(EC.url_contains(admin_url))
     if present:
         self.browser.find_element_by_link_text(present)
     if absent:
         with self.assertRaises(NoSuchElementException):
             self.browser.find_element_by_link_text(absent)
Exemplo n.º 6
0
 def test_confirm_order(self):
     """After filling the form we should be able to confirm an Order."""
     self.append_products_to_cart()
     self.fill_contacts_data()
     self.submit_form()
     self.wait.until(EC.url_contains(self.success_order_url))
     self.assertIn(
         reverse_custom_page('order-success'),
         self.browser.current_url,
     )
Exemplo n.º 7
0
    def test_autocomplete_by_vendor_code(self):
        """Autocomplete should work by product's vendor code."""
        product_vendor_code = Product.objects.first().vendor_code

        self.fill_input(product_vendor_code)
        first_item = self.autocomplete.find_element_by_css_selector(':first-child')
        first_item.click()
        self.wait.until(EC.url_contains('/catalog/products/'))

        test_vendor_code = self.browser.find_element_by_class_name('product-article').text

        self.assertIn(str(product_vendor_code), test_vendor_code)
Exemplo n.º 8
0
    def test_change_cart_and_pay_with_yandex_kassa(self):
        """
        The same as `test_pay_with_yandex_kassa`, but with the detail.

        Appending products to cart on order page
        suddenly breaks yandex kassa payment type.
        """
        success_page_domain = self.YA_KASSA_INNER_DOMAIN
        self.append_products_to_cart()
        self.fill_contacts_data()  # Ignore CPDBear
        self.select_payment_type('AC')
        self.submit_form()
        self.wait.until(EC.url_contains(success_page_domain))
        self.assertIn(success_page_domain, self.browser.current_url)
Exemplo n.º 9
0
    def test_tree_redirect_to_table_editor_page(self):
        """Test redirect to table editor page by context click at tree's item."""
        self.wait_page_loading()
        self.open_js_tree_nodes()
        self.click_jstree_context_menu_items(0)
        self.wait.until(EC.url_contains('/editor/'))
        test_h1 = self.wait.until(EC.presence_of_all_elements_located(
            (By.TAG_NAME, 'h1')
        ))[1].text

        self.assertEqual(test_h1, 'Табличный редактор')

        test_search_value = (
            self.browser
            .find_element_by_id('search-field')
            .get_attribute('value')
        )
        self.assertTrue(len(test_search_value) > 0)
Exemplo n.º 10
0
    def test_order_email(self):
        codes = self.browser.find_elements_by_class_name(
            'order-table-product-id')
        clean_codes = [code.text for code in codes]

        self.append_products_to_cart()
        final_price = self.browser.find_element_by_id('cart-page-sum').text[:-5]

        self.fill_contacts_data()
        self.submit_form()
        self.wait.until(EC.url_contains(self.success_order_url))
        self.assertEqual(len(mail.outbox), 1)
        sent_mail_body = mail.outbox[0].body

        self.assertIn('Наличные', sent_mail_body)
        self.assertIn('+7 (222) 222 22 22', sent_mail_body)
        self.assertIn('*****@*****.**', sent_mail_body)
        self.assertIn(f'tel:{settings.SHOP["cps_phone"]}', sent_mail_body)
        self.assertIn(settings.SHOP['cps_formatted_phone'], sent_mail_body)

        for code in clean_codes:
            self.assertInHTML(
                '<td align="left"'
                'style="border-bottom:1px solid #E4E4E4;padding:10px">{0}</td>'
                .format(code),
                sent_mail_body
            )
            self.assertIn(
                '<a href="https://www.shopelectro.ru{0}"'
                .format(reverse('product', args=(code,))),
                sent_mail_body
            )

        self.assertInHTML(
            '<td align="right" style="padding:5px 10px">{0} руб.</td>'
            .format(final_price),
            sent_mail_body
        )
Exemplo n.º 11
0
    def test_succeed(self):
        """
        http://strzw058051/SMARTSolutions/
        valid username: admin
        valid password: Admin
        Assert '/Portal/Home' is contained in the url
        """
        time.sleep(5)
        login_ele = self.driver.find_element(By.ID, 'txtLoginid')
        login_ele.send_keys('admin')

        password_ele = self.driver.find_element(By.ID, 'txtPassword')
        password_ele.send_keys('Admin')

        login_ele_btn = self.driver.find_element(By.ID, 'btnloginText')
        login_ele_btn.click()

        time.sleep(10)

        # self.assertIn(member='Notification Center',
        #               container =self.driver.page_source,
        #               msg='Scheduling & Notification Center is visible in the page')
        WebDriverWait(self.driver, 60).until(EC.url_contains('/Portal/Home'))
Exemplo n.º 12
0
    def confirm_passenger(self):
        """
        确认乘客和席位信息
        :return: None
        """
        # 等待页面跳转到确认乘客信息页面
        WebDriverWait(self.driver, 1000).until(
            EC.url_contains(
                "https://kyfw.12306.cn/otn/confirmPassenger/initDc"))

        # 等待乘客信息元素被加载进来
        WebDriverWait(self.driver, 1000).until(
            EC.presence_of_element_located(
                (By.XPATH, "//ul[@id='normal_passenger_id']/li")))

        # 等待席位元素被加载进来
        WebDriverWait(self.driver, 1000).until(
            EC.presence_of_element_located(
                (By.XPATH, "//select[@id='seatType_1']/option")))

        # 提取所有的乘客的label标签
        passenger_labels = self.driver.find_elements_by_xpath(
            "//ul[@id='normal_passenger_id']/li/label")

        # 把需要购买票的用户勾选上
        for passenger_label in passenger_labels:
            if passenger_label.text in self.passengers:
                passenger_label.click()

        # 选择席位
        seat_select = Select(self.driver.find_element_by_id("seatType_1"))
        for seat_type in self.trains[self.current_number]:
            try:
                seat_select.select_by_value(seat_type)
                self.current_seat_type = seat_type
            except NoSuchElementException:
                continue
            else:
                break

        # 等待提交订单按钮可用,然后点击
        WebDriverWait(self.driver, 1000).until(
            EC.element_to_be_clickable((By.ID, "submitOrder_id")))
        submit_order_btn = self.driver.find_element_by_id("submitOrder_id")
        submit_order_btn.click()

        # 等待核对订单的模态对话框弹出来
        WebDriverWait(self.driver, 1000).until(
            EC.presence_of_element_located(
                (By.CLASS_NAME, "dhtmlx_window_active")))
        WebDriverWait(self.driver, 1000).until(
            EC.element_to_be_clickable((By.ID, "qr_submit_id")))
        confirm_submit_btn = self.driver.find_element_by_id("qr_submit_id")
        try:
            while confirm_submit_btn:
                confirm_submit_btn.click()
                confirm_submit_btn = self.driver.find_element_by_id(
                    "qr_submit_id")
        except ElementNotVisibleException:
            pass
        print("恭喜!成功抢到【%s】次列车【%s】席位,请在30分钟内完成付款!" %
              (self.current_number, self.current_seat_type))

        time.sleep(100)
Exemplo n.º 13
0
def verify_sign_in_page_opens(context):
    context.driver.wait.until(
        EC.url_contains('https://www.amazon.com/ap/signin'),
        f'Url {context.driver.current_url} does not include https://www.amazon.com/ap/signin'
    )
Exemplo n.º 14
0
)  #open internet
website = "https://test.on.ag/online-assistent/start"
chrome.get(website)

# 2 Click on Beitrag Berechnen tile
berufstatus_url = "/berechnen/berufsstatus"
tarifauswahl_url = "/berechnen/tarif-auswahl"
eingabe_url = "/berechnen/krankenversicherung/eingabe"

mein_beitrag_locator = "//oa-tile[contains(@ng-reflect-navigate-to,'" + berufstatus_url + "')]"
mein_beitrag = chrome.find_element_by_xpath(xpath=mein_beitrag_locator)

mein_beitrag.click()

wait = WebDriverWait(chrome, 10)
wait.until(EC.url_contains(berufstatus_url))
new_url = chrome.current_url

assert berufstatus_url in new_url
print("Correct URL!")
# Switched page to Berufsstatus

# 4 Select Student oder in Ausbildung

beruf_locator = "//select"
weiter_button_locator = '//button[contains(text(), "Weiter")]'

weiter_button = chrome.find_element_by_xpath(xpath=weiter_button_locator)
# BEFORE providing data into Beruf - Weiter button MUST NOT be enabled

check_disabled()
Exemplo n.º 15
0
 def check_current_url(self, uri):
     WebDriverWait(self.driver, 10).until(ec.url_contains(uri))
Exemplo n.º 16
0
 def wait_until_url_contains(self, url, time_out: int = 20):
     try:
         WebDriverWait(self.driver,time_out).until(EC.url_contains(url))
     except TimeoutException:
         raise TimeoutException(f"After {time_out} seconds of wait the page url doens't contain {url}")
Exemplo n.º 17
0
 def wait_until_not_url(self, url, timeout=_DEFAULT_TIMEOUT):
     self.get_wait(timeout).until_not(ec.url_contains(url))
Exemplo n.º 18
0
 def url_contains(self, url):
     return Condition(ec.url_contains(url), self.driver)
Exemplo n.º 19
0
 def url_contains(url: str, timeout: int = 10):
     return WebDriverWait(CONTEXT.driver, timeout).until(
         expected_conditions.url_contains(url),
         f"Current url did not contain '{url}' as expected")
Exemplo n.º 20
0
_path_to_chromedriver = "C:\\Users\\zane.mertes\\PycharmProjects\\chromedriver\\chromedriver.exe"
# 1 Open Online Assistent
chrome_webdriver = webdriver.Chrome(
    executable_path=_path_to_chromedriver)  # open internet
# open internet

wait = WebDriverWait(chrome_webdriver, 20)

website = _base_url + StartPage.my_url
chrome_webdriver.get(website)

page = StartPage(driver=chrome_webdriver)

# 2 Click on Beitrag Berechnen tile
page.find_beitrag_berechnen_button.click()
wait.until(EC.url_contains(BerufsStatusPage.my_url))

# 3. Switch page to Berufsstatus
page = BerufsStatusPage(driver=chrome_webdriver)
# 4 Select Student oder in Ausbildung
# BEFORE providing data into Beruf - Weiter button MUST NOT be enabled

page.check_weiter_button_is_disabled()
page.berufstatus_select.select_by_visible_text("Angestellter")
page.income_input.send_keys("100000")
# AFTER providing data into Beruf - Weiter button MUST be enabled
page.check_weiter_button_is_enabled()

#WeiterButtonPage.weiter_button.click()

wb = chrome_webdriver.find_element_by_xpath(
Exemplo n.º 21
0
 def assert_path_in_current_url(self, path: str):
     assert_path_in_url = WebDriverWait(self.driver, 100).until(
         EC.url_contains(url=path))
     assert assert_path_in_url is True
Exemplo n.º 22
0
 def go_to_cart(self):
     self.click(self.CART_LOCATOR)
     self.wait.until(EC.url_contains(self.order_page_url))
Exemplo n.º 23
0
def step(context, url):
    assert ec.url_contains(url)
Exemplo n.º 24
0
def extractLinksPisos(URLText, startTime,saveDir, dataFileName ):
    #INICIO FIREFOX
    #########################################################################################
    prefix = "MF_" #Para saber desde qu� hebra ejecuto cada cosa uso siempre el prefijo del navegador antes de mostrar un mensaje
    print(prefix,'Iniciando Firefox')
    caps = DesiredCapabilities().FIREFOX
    caps["applicationCacheEnabled"]= "true"
    caps["pageLoadStrategy"] = "normal"
    profile = webdriver.FirefoxProfile()
    profile.set_preference('javascript.enabled', True)
    options = webdriver.FirefoxOptions()
    options.add_argument("--enable-javascript")
    options.add_argument("--disable-plugins-discovery")
    options.add_argument('--disable-extensions')  
    options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")
    profile.update_preferences()
    if WithProxy==1 :
        driver = webdriver.Firefox(desired_capabilities=caps,  proxy=proxy, firefox_profile=profile, options=options)
    if WithProxy == 0 :
        driver = webdriver.Firefox(desired_capabilities=caps, firefox_profile=profile, options=options)#executable_path='/your/path/to/geckodriver'
    wait = WebDriverWait(driver,waitTimeDefault)
    waitLong = WebDriverWait(driver,waitTimeLong)
    driver.maximize_window()
    ###########################################################################################
    sleepRand()
    driver.get(URLText)
    waitLong.until(EC.url_contains(URLText))
    sleepRand()
    try:
        wait.until(EC.presence_of_element_located((By.XPATH,"//button[@id='didomi-notice-agree-button']"))).click()
        sleepRand()
    except:
        print("No he podido hacer click en la cookies...")
    sleepRand()
    StringNumObjects = wait.until(EC.presence_of_element_located((By.XPATH,"//span[@class='total-results']"))).text 
    
    NumObjects = int(StringNumObjects.split()[0])
    print("Hay ", NumObjects, " resultados")
    
    df = pd.DataFrame(columns = ['Link', 'Título','Precio', 'metros cuadrados','Orientación','Planta','Referencia del portal', 'Inmobiliaria', 'número de fotos','Tipo de anuncio', 'Descripción del anuncio'])
    numPthotos = []
    numPthotos.clear()
    linkMainSearch=driver.current_url
    try:
        links=driver.find_elements_by_xpath("//div[@id='parrilla']/div[@data-listado-row='true']//a[@class='anuncioLink']")
        
    except:
        print("ERROR : extrayendo primer link... intento otra vez")
        time.sleep(sleepTime*2)
        try:
            links=driver.find_elements_by_xpath("//div[@class='content parrilla']/div[@class='gridList Listado' and @id='parrilla']/div[@data-listado-row='true']//a[@class='anuncioLink']")
        except:
            print("ERROR : No encuentro los links...")
    exit =NumObjects
    allLinks = []
    allLinks.clear()
    for i in links:
        try:
            allLinks.append(i.get_attribute('href'))
            #print("Extraido el link :", i.get_attribute('href'))
        except:
            print(prefix , 'EEROR : Link ERROR')
    #checkStatus(linkHouse,exit,numObjectsm,driver, wait, waitLong)
    linkActual = 0
    while exit > 0:
        print("Extrayendo link ", NumObjects-exit, " de un total de ", NumObjects, ", hay ", len(links)-linkActual, " links más de esta pagina")
        linkHouse=allLinks[linkActual]
        print(linkHouse)
        driver.get(linkHouse)
        printElapsedTieme(startTime)
        sleepRand()
        #EXTRAIGO LOS DATOS
        
        v_titleHouse = getTitle(wait)
        print(v_titleHouse)
        v_priceHouse = getPrice(wait)
        if(debug==True): print(v_priceHouse, " €")
        v_areaHouse = getArea(wait)
        if(debug==True): print(v_areaHouse, " m^2")
        v_reference = getReference(wait, driver)
        if(debug==True): print(v_reference)
        v_seller = getSeller(wait, driver)
        if(debug==True): print(v_seller)
        numPthotos = getNumberOfPhotos(wait)
        if(debug==True): print(numPthotos)
        v_orientacion = getOrientation(wait)
        if(debug==True): print(v_orientacion)
        v_comment = getComment(wait, driver)
        v_houseType = getHouseType(v_titleHouse)
        if(debug==True): print("Tipo de oferta : ",v_houseType)
        if(v_houseType == 'Piso' or v_houseType == 'Apartamento'):
            v_floor = getFloor(wait)
        else:
            v_floor = 'No es un piso ni un apartamento'
        if(debug==True): print(v_floor)
        
        getPhotography(wait,NumObjects-exit, dataFileName, saveDir)

        df.loc[len(df)] = [linkHouse,v_titleHouse,v_priceHouse ,v_areaHouse,v_orientacion,v_floor, v_reference,v_seller, numPthotos, v_houseType, v_comment]
        
        #linkHouse = ClickNextPageRight(wait,waitLong,driver)
        linkActual = linkActual+1
        if(linkActual >= len(links) and exit>1):
            print("Obteniendo links de la siguiente página")
            driver.get(linkMainSearch)
            sleepRand()
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            sleepRand()
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            sleepRand()
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR," body"))).send_keys(Keys.PAGE_DOWN)
            sleepRand()
            try:
                wait.until(EC.presence_of_element_located((By.XPATH,"//a[@id='lnkPagSig']"))).click()
            except:
                try:
                    wait.until(EC.presence_of_element_located((By.XPATH,"//span[contains(text(),'Siguiente')]"))).click()
                except:
                    print("ERROR : haciendo click en siguiente página")
            linkMainSearch=driver.current_url
            try:
                links=driver.find_elements_by_xpath("//div[@id='parrilla']/div[@data-listado-row='true']//a[@class='anuncioLink']")
            except:
                print("ERROR : extrayendo primer link... intento otra vez")
                time.sleep(sleepTime*2)
                try:
                    links=driver.find_elements_by_xpath("//div[@class='content parrilla']/div[@class='gridList Listado' and @id='parrilla']/div[@data-listado-row='true']//a[@class='anuncioLink']")
                except:
                    print("ERROR : No encuentro los links...")
            allLinks = []
            allLinks.clear()
            for i in links:
                try:
                    allLinks.append(i.get_attribute('href'))
                    #print("Extraido el link :", i.get_attribute('href'))
                except:
                    print(prefix , 'EEROR : Link ERROR')
            print("Extraidos ", len(allLinks), " links")
            linkActual=0
        exit = exit-1
    driver.close()
    #TODOS LOS DATOS EXTRAIDOS
    #################################################################
    print(prefix,'Iniciando : Copia de datos al excel')
    frames = [df]
    df_copy = pd.concat(frames, axis=0, join='outer', ignore_index=True,
              keys=None, levels=None, names=None, verify_integrity=False,
              copy=True)
    df_copy.to_csv(saveDir + "\datos_"+dataFileName+'.csv', encoding='utf-8', index=False)
    print(prefix,'Finalizado : Copia de datos al excel')
    print("Los datos estan en ",saveDir)
    printElapsedTieme(startTime)
Exemplo n.º 25
0
seperator = ", "

# Start process
file = open(state, 'w+')
driver = webdriver.Chrome()
driver.get(home)
try:
    # time.sleep(1)
    # closeButton = wait(driver, 2).until(EC.presence_of_element_located((By.CLASS_NAME,"close")))
    # closeButton.click();
    time.sleep(1)
    assert home in driver.current_url
    searchButton = wait(driver, 2).until(EC.presence_of_element_located((By.CSS_SELECTOR,"span.input-group-addon > button")))
    # time.sleep(2)
    searchButton.click()
    wait(driver, 2).until(EC.url_contains(search))
    action = ActionChains(driver)
    title = "name, address, regNo, date_of_registration, type_of_registration, contact_number, email_address"
    while True:
        rowSearchList = driver.find_elements_by_css_selector("div.row.search_result_list")
        for row in rowSearchList:
            details = str()
            name = row.find_element_by_tag_name("h1").text
            parah = row.find_elements_by_tag_name("p")
            address = parah[0].text
            regNo = parah[1].text
            content = row.find_element_by_css_selector("div.table-responsive").find_elements_by_tag_name("td")
            date_of_registration = content[0].text
            type_of_registration = content[1].text
            contact_number = content[2].text
            email_address = content[3].text
Exemplo n.º 26
0
options.add_argument("enabled")
options.add_argument("disable-infobars")
options.add_argument("autoplay-policy=no-user-gesture-required")

driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, default_wait_time)
zoom_link = os.environ['ZOOM_LINK']
driver.get(zoom_link)
sleep(5)
el = wait.until(
    lambda d: d.find_element_by_link_text('Join from Your Browser'))
el.click()
#driver.find_element_by_link_text('Join from Your Browser').click()
# Login
try:
    wait.until(EC.url_contains('idp.tuc.gr/'))
    institutional_login(driver)
except TimeoutException:
    pass

# Join Zoom call
driver.find_element_by_id('joinBtn').click()
# Select computer audio
#driver.find_element_by_css_selector('.join-audio-by-voip > button').click()

join_audio_btn = wait.until(
    lambda d: d.find_element_by_css_selector('.join-audio-by-voip > button'))
join_audio_btn.click()
#driver.find_element_by_tag_name('body').send_keys(Keys.TAB + Keys.ENTER)
mute_mic(driver)
#driver.fullscreen_window()
Exemplo n.º 27
0
def checkSort(browser):
    try: 
        WebDriverWait(browser, delay).until(EC.url_contains('sort=date'))
    except: 
        browser.get(browser.current_url + '&sort=date')
Exemplo n.º 28
0
# Would advise user to mute volume before continuing
# select the amount of games that you want to play
loop = input("Enter how many games you want to play: ")
loopInt = int(loop)
games = 0

while games < loopInt:
    # click the "Battle!" button and wait 60 secs for a game to occur
    clicker.find_element_by_xpath(
        '//button[@class="button mainmenu1 big"]').click()

    try:  # found a battle against opponent

        # turns on timer and sends message to opponent
        WebDriverWait(clicker,
                      600).until(EC.url_contains('gen8challengecup1v1'))
        try:
            clicker.find_element_by_xpath(
                '//button[@class="button timerbutton"]').click()
            clicker.find_element_by_xpath('//button[@name="timerOn"]').click()
        except:
            pass
# messages intro for opponent
        clicker.find_element_by_xpath('//textarea[@placeholder]').send_keys(
            'GL HF!')
        clicker.find_element_by_xpath('//textarea[@placeholder]').submit()

        # gets the names of each player
        names = clicker.find_elements_by_xpath('//div[@class="trainer"]')
        start = 'Battle started between ' + names[0].text + ' and ' + names[
            1].text + '!'
Exemplo n.º 29
0
 def verifyPageUpdatedTo(self, page):
     self.wait.until(EC.url_contains(page))
     self.pageTitle = self.getCurrentPageTitle()
Exemplo n.º 30
0
def parse_whoscored(url, driver, db):

    URL = url
    MAIN_TABLE = []
    MAIN_TABLE_SQL = []
    CHARACTERISTIC_TABLE = []
    CHARACTERISTIC_TABLE_SQL = []
    HT_TABLE_STAT = []
    FT_TABLE_STAT = []
    STAT_SQL = []

    driver.get(url)
    try:
        wait_res = WebDriverWait(driver,
                                 60).until(EC.url_contains("https://1xbet."))
    except TimeoutException:
        pass

    #driver.execute_script(script_scroll_down, 700)

    try:
        CHARACTERISTIC_TABLE += parse_characteristic(driver)
    except AssertionError:
        print(traceback.format_exc())
        CHARACTERISTIC_TABLE += parse_characteristic(driver)
    CHARACTERISTIC_TABLE_SQL += sql_columns_of_url
    CHARACTERISTIC_TABLE_SQL += sql_columns_of_characteristic
    assert len(CHARACTERISTIC_TABLE_SQL) == (len(CHARACTERISTIC_TABLE) + 1)

    assert url.find("Show") != -1
    url = url.replace("Show", "Preview")
    driver.get(url)
    try:
        wait_res = WebDriverWait(driver,
                                 60).until(EC.url_contains("https://1xbet."))
    except TimeoutException:
        pass

    try:
        CHARACTERISTIC_TABLE += parse_probable_stat(driver)
    except AssertionError:
        print(traceback.format_exc())
        CHARACTERISTIC_TABLE += parse_probable_stat(driver)

    CHARACTERISTIC_TABLE_SQL += sql_columns_of_probable_stat
    assert len(CHARACTERISTIC_TABLE_SQL) == (len(CHARACTERISTIC_TABLE) + 1)

    assert url.find("Preview") != -1
    url = url.replace("Preview", "Live")
    driver.get(url)
    try:
        wait_res = WebDriverWait(driver,
                                 60).until(EC.url_contains("https://1xbet."))
    except TimeoutException:
        pass

    CHARACTERISTIC_TABLE.insert(0, "'" + url + "'")
    MAIN_TABLE.append("'" + url + "'")
    HT_TABLE_STAT.append("'" + url + "'")
    FT_TABLE_STAT.append("'" + url + "'")

    MAIN_TABLE_SQL += sql_columns_of_url
    STAT_SQL += sql_columns_of_url
    assert len(MAIN_TABLE_SQL) == len(MAIN_TABLE)

    home_stat = parse_yc_rc_goals(xpath_to_home_stat, driver)
    away_stat = parse_yc_rc_goals(xpath_to_away_stat, driver)

    if home_stat[0] > away_stat[0]:
        MAIN_TABLE.append('1')
    elif home_stat[0] < away_stat[0]:
        MAIN_TABLE.append('2')
    elif home_stat[0] == away_stat[0]:
        MAIN_TABLE.append('0')
    MAIN_TABLE += home_stat
    MAIN_TABLE += away_stat

    MAIN_TABLE_SQL += sql_columns_of_time_stat
    assert len(MAIN_TABLE_SQL) == len(MAIN_TABLE)

    try:
        FT_TABLE_STAT += parse_live_table(driver)
    except AssertionError:
        print(traceback.format_exc())
        FT_TABLE_STAT += parse_live_table(driver)
    STAT_SQL += sql_columns_of_stat
    assert len(STAT_SQL) == len(FT_TABLE_STAT)

    wait_res = WebDriverWait(driver, 30).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, css_to_time_scroll)))
    action = ActionChains(driver)
    elem = driver.find_elements_by_css_selector(css_to_time_scroll)
    action.move_to_element(elem[1])
    X1 = elem[1].location.get('x')
    new_possition = 630 - X1
    action.drag_and_drop_by_offset(elem[1], new_possition, 0).perform()

    try:
        HT_TABLE_STAT += parse_live_table(driver)
    except AssertionError:
        print(traceback.format_exc())
        HT_TABLE_STAT += parse_live_table(driver)
    assert len(HT_TABLE_STAT) == len(STAT_SQL)

    WebDriverWait(driver,
                  30).until(EC.presence_of_element_located(
                      (By.XPATH, referee)))

    try:
        referee_sub = "'" + driver.find_element_by_xpath(
            referee).text.strip() + "'"
    except:
        referee_sub = "'" + 'Mike Dean' + "'"
    MAIN_TABLE.append(referee_sub)
    MAIN_TABLE_SQL += sql_columns_of_referee
    assert len(MAIN_TABLE) == len(MAIN_TABLE_SQL)

    FIRST_STAT = [str('"' + URL + '"')]
    SECOND_STAT = [str('"' + URL + '"')]
    THIRD_STAT = [str('"' + URL + '"')]
    FOURTH_STAT = [str('"' + URL + '"')]
    FIFTH_STAT = [str('"' + URL + '"')]
    SIX_STAT = [str('"' + URL + '"')]

    FIRST_STAT += move_part(driver, -323, parse_live_table, css_to_time_scroll)
    SECOND_STAT += move_part(driver, 156, parse_live_table, css_to_time_scroll)
    THIRD_STAT += move_part(driver, 154, parse_live_table, css_to_time_scroll)
    FOURTH_STAT += move_part(driver, 185, parse_live_table, css_to_time_scroll)
    FIFTH_STAT += move_part(driver, 170, parse_live_table, css_to_time_scroll)
    SIX_STAT += move_part(driver, 155, parse_live_table, css_to_time_scroll)

    elem = driver.find_element_by_xpath(xpath_to_chalkboard)
    action = ActionChains(driver)
    action.move_to_element(elem)
    action.click(elem)
    action.perform()

    ##    driver.execute_script(script_scroll_down, 1100)
    # 1 to 90
    try:
        FT_TABLE_STAT += parse_chalkboard(driver)
        FT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_home)
        FT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_away)
    except AssertionError:
        print(traceback.format_exc())
        FT_TABLE_STAT += parse_chalkboard(driver)
        FT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_home)
        FT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_away)

    STAT_SQL += sql_columns_of_chulkboard
    assert len(STAT_SQL) == len(FT_TABLE_STAT)

    wait_res = WebDriverWait(driver, 30).until(
        EC.presence_of_element_located(
            (By.CSS_SELECTOR, css_to_time_scroll_chalkboard)))
    elem = driver.find_elements_by_css_selector(css_to_time_scroll_chalkboard)
    action = ActionChains(driver)
    action.move_to_element(elem[1])
    X1 = elem[1].location.get('x')
    new_possition = 630 - X1
    action.drag_and_drop_by_offset(elem[1], new_possition, 0).perform()

    try:
        HT_TABLE_STAT += parse_chalkboard(driver)
        HT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_home)
        HT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_away)
    except AssertionError:
        print(traceback.format_exc())
        HT_TABLE_STAT += parse_chalkboard(driver)
        HT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_home)
        HT_TABLE_STAT += parse_shots_zones(driver, xpath_to_shots_detail_away)
    assert len(HT_TABLE_STAT) == len(STAT_SQL)

    FIRST_STAT += move_part(driver, -323, parse_chalkboard,
                            css_to_time_scroll_chalkboard)
    SECOND_STAT += move_part(driver, 155, parse_chalkboard,
                             css_to_time_scroll_chalkboard)
    THIRD_STAT += move_part(driver, 155, parse_chalkboard,
                            css_to_time_scroll_chalkboard)
    FOURTH_STAT += move_part(driver, 185, parse_chalkboard,
                             css_to_time_scroll_chalkboard)
    FIFTH_STAT += move_part(driver, 170, parse_chalkboard,
                            css_to_time_scroll_chalkboard)
    SIX_STAT += move_part(driver, 155, parse_chalkboard,
                          css_to_time_scroll_chalkboard)

    print(MAIN_TABLE)
    print(CHARACTERISTIC_TABLE)
    print(FT_TABLE_STAT)
    print(HT_TABLE_STAT)
    print(FIRST_STAT)
    print(SECOND_STAT)
    print(THIRD_STAT)
    print(FOURTH_STAT)
    print(FIFTH_STAT)
    print(SIX_STAT)

    MAIN_TABLE_SQL_string = ""
    for sql_column, stat in zip(MAIN_TABLE_SQL, MAIN_TABLE):
        MAIN_TABLE_SQL_string += sql_column + "=" + str(stat) + ", "
    assert len(MAIN_TABLE_SQL_string)

    cursor = db.cursor()

    assert cursor.execute("SELECT * FROM " + tb_name_main + " WHERE url='" +
                          URL + "';")
    sql = "UPDATE " + tb_name_main + " SET " + str(
        MAIN_TABLE_SQL_string[:-2]) + " WHERE url='" + URL + "';"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_characteristic + "(" + ",".join(
        CHARACTERISTIC_TABLE_SQL) + ") VALUES (" + ",".join(
            CHARACTERISTIC_TABLE) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_full_time + "(" + ",".join(
        STAT_SQL) + ") VALUES (" + ",".join(FT_TABLE_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_half_time + "(" + ",".join(
        STAT_SQL) + ") VALUES (" + ",".join(HT_TABLE_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_1_15_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(FIRST_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_15_30_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(SECOND_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_30_45_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(THIRD_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_45_60_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(FOURTH_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_60_75_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(FIFTH_STAT) + ");"
    cursor.execute(sql)

    sql = "INSERT INTO " + tb_name_75_90_stat + "(" + ",".join(
        STAT_SQL[:-38]) + ") VALUES (" + ",".join(SIX_STAT) + ");"
    cursor.execute(sql)
    db.commit()

    print("DONE!")
Exemplo n.º 31
0
        driver.find_element_by_name('TOL').send_keys(Keys.CONTROL + 'a')
        driver.find_element_by_name('TOL').send_keys(pepComb[1])

        driver.find_element_by_id('InputSource-DATAFILE').send_keys(
            Peaklist_Path + '/' + str(peaklist))

        driver.find_element_by_xpath(
            '//*[@id="plainContent"]/form/table/tbody/tr[16]/td[2]/b/input'
        ).submit()
        print(Fore.CYAN + Style.DIM + 'Searching...')

        try:
            waiter = wdWait(driver, 50).until(
                url_contains(
                    'https://proteomicsresource.washington.edu/mascot/cgi/master_results.pl'
                ))
            Result = driver.find_element_by_xpath(
                '/html/body/font[1]/pre').text
            Protein_name = str(
                driver.find_element_by_xpath(Variable_xpath).text)[36:].split(
                    'OS=')[0].strip(',').strip()
            Mascot_ID = str(
                driver.find_element_by_xpath(Variable_xpath).text)[17:].split(
                    'for')[1].split(',')[0].strip()
        except:
            Result = 'Page not valid for this peaklist. Proceeding...'

        try:
            topScore = int(
                str(driver.find_element_by_xpath(Variable_xpath).text)
Exemplo n.º 32
0
    chrome_options=options
)  # Optional argument, if not specified will search path.

driver.get(url)
driver.maximize_window()

username = driver.find_element_by_name('username').send_keys(user_arg)
password = driver.find_element_by_name('password').send_keys(pass_arg)

login_button = driver.find_element_by_class_name('login2017-actions-button')
login_button.click()

list_of_url = []
time.sleep(5)  # Let the user actually see something!
likedurl = 'https://www.okcupid.com/who-you-like'
WebDriverWait(driver, 1).until(EC.url_contains("home"))

driver.get(likedurl)
WebDriverWait(driver, 1).until(EC.url_contains("who-you-like"))

all_likeduser = driver.find_elements_by_class_name('userrow-inner')
for onlineuser in all_likeduser:
    print(" ")
    if (onlineuser.find_element_by_class_name(
            'userrow-username').find_elements_by_xpath(
                ".//span[@class='onlinedot userrow-username-online']")):
        print(
            onlineuser.find_element_by_class_name(
                'userrow-username-name').text)
        liked_profile = onlineuser.get_attribute("href")
        list_of_url.append(liked_profile)
Exemplo n.º 33
0
def buy_ipx():
    if module_exist("selenium") is False:
        os.system("pip3 install selenium")
    from selenium import webdriver
    from selenium.common.exceptions import TimeoutException
    result = get_string_from_command("phantomjs --help")
    if re.search(r"(not found)|(不是内部或外部命令)|(Unknown command)", result,re.I):
        if platform.system() == "Darwin":
            os.system("brew install phantomjs")
        elif platform.system() == 'Linux':
            os.system("echo y | apt-get install phantomjs")
        elif platform.system() == 'Windows':
            import wget --no-cache
            try:
                wget --no-cache.download(
                    "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip", out="phantomjs.zip")
            except:
                print(
                    "Please download phantomjs from the official site and add the executeable file to your path")
                input("下载速度太慢,还是手工用迅雷下载吧,下载后将可执行文件phantomjs.exe存放到PATH中,再按任意键继续...")
    import time
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait 
    from selenium.webdriver.support import expected_conditions

    if proxy_url == "" or proxy_url == 0:
        service_args_value = ['--ignore-ssl-errors=true',
                              '--ssl-protocol=any', '--web-security=false']
    if proxy_url != "" and proxy_url != 0:
        proxy_type = proxy_url.split(":")[0]
        proxy_value_with_type = proxy_url.split("/")[-1]
        service_args_value = ['--ignore-ssl-errors=true', '--ssl-protocol=any', '--web-security=false',
                              '--proxy=%s' % proxy_value_with_type, '--proxy-type=%s' % proxy_type]
        #service_args_value.append('--load-images=no')  ##关闭图片加载
        service_args_value.append('--disk-cache=yes')  ##开启缓存

    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    dcap = dict(DesiredCapabilities.PHANTOMJS)

    ua = "Mozilla/4.0 (Windows; U; Windows NT 5.0; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.33 Safari/532.0"
    #headers = {'User-Agent': '%s' % get_random_ua(),'Cookie': '%s' % cookie}
    if cookie!="":
        headers = {'User-Agent': '%s' % ua,'Cookie': '%s' % cookie}
    else:
        headers = {'User-Agent': '%s' % ua}
    for key in headers:
        capability_key = 'phantomjs.page.custom_headers.{}'.format(key)
        webdriver.DesiredCapabilities.PHANTOMJS[capability_key] = headers[key]
    driver = webdriver.PhantomJS(service_args=service_args_value)

    driver.implicitly_wait(300)
    driver.set_page_load_timeout(300)

    print("目前没有登录,现在访问收藏夹,尝试跳转到登录页面")
    driver.get("https://www.apple.com/cn/shop/favorites")

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.NAME, 'login-apple_id')
      ) 
    )
    user_text_box=driver.find_element_by_name('login-apple_id')
    user_text_box.clear()
    user_text_box.send_keys(apple_id)
    pass_text_box=driver.find_element_by_name('login-password')
    pass_text_box.clear()
    pass_text_box.send_keys(apple_id_pass)
    login_button=driver.find_element_by_id('sign-in')
    print("现在点击登录按钮")
    login_button.click()

    import random
    #driver.get_screenshot_as_file("/tmp/PhantomJSPic")
    title = driver.title
    print(title)
    content = driver.page_source


    while True:
        pic_links=driver.find_elements_by_class_name('relatedlink')
        if pic_links and len(pic_links)>0:
            print(len(pic_links))
            break
        else:
            time.sleep(1)
            continue

    #attention!!!!!!!!这里要修改,[1]和[2]是iphonex
    pic_links[try_index-1].click()

    #driver.get_screenshot_as_file("/tmp/PhantomJSPic0")


    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.NAME, 'add-to-cart')
      ) 
    )


    add_to_cart_link=driver.find_element_by_name('add-to-cart')
    add_to_cart_link.click()
    print("现在加入到购物车")

    #driver.get_screenshot_as_file("/tmp/PhantomJSPic1")


    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID, 'cart-actions-checkout')
      ) 
    )


    jie_zhang_link=driver.find_element_by_id('cart-actions-checkout')
    print("现在点击结帐")
    jie_zhang_link.click()

    #driver.get_screenshot_as_file("/tmp/PhantomJSPic2")

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.NAME, 'login-apple_id')
      ) 
    )
    user_text_box=driver.find_element_by_name('login-apple_id')
    user_text_box.clear()
    user_text_box.send_keys('xxx')
    pass_text_box=driver.find_element_by_name('login-password')
    pass_text_box.clear()
    pass_text_box.send_keys('xxx')
    login_button=driver.find_element_by_id('sign-in')
    print("现在点击登录按钮")
    login_button.click()
    driver.get_screenshot_as_file("/tmp/PhantomJSPic3")

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'cart-continue-button')
      ) 
    )
    continue_button1=driver.find_element_by_id('cart-continue-button')
    continue_button1.click()
    continue_button2=driver.find_element_by_id('shipping-continue-button')
    continue_button2.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'payment-form-options-Alipay-0')
      ) 
    )

    zhifubao_button=driver.find_element_by_id('payment-form-options-Alipay-0')
    zhifubao_button.click()
    payment_continue_button=driver.find_element_by_id('payment-continue-button')
    payment_continue_button.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'invoice-next-step')
      ) 
    )
    
    invoice_next_step_button=driver.find_element_by_id('invoice-next-step')
    invoice_next_step_button.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'terms-accept')
      ) 
    )

    terms_accept_button=driver.find_element_by_id('terms-accept')
    terms_accept_button.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'terms-continue-button')
      ) 
    )

    terms_continue_button=driver.find_element_by_id('terms-continue-button')
    terms_continue_button.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'place-order-button')
      ) 
    )

    place_order_button=driver.find_element_by_id('place-order-button')
    place_order_button.click()

    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID ,'pay_now')
      ) 
    )

    pay_now_button=driver.find_element_by_id('pay_now')
    pay_now_button.click()


    WebDriverWait(driver, 300).until( 
      expected_conditions.element_to_be_clickable( 
        (By.ID,'J_tLoginId')
      ) 
    )


    zhifubao_username_box=driver.find_element_by_id('J_tLoginId')
    zhifubao_username_box.click()
    zhifubao_username_box.clear()
    zhifubao_username_box.send_keys(zhifubao_username)

    zhifubao_pass_box=driver.find_element_by_id('pay_passwd_rsainput')
    zhifubao_pass_box.click()
    #zhifubao_pass_box.clear()
    zhifubao_pass_box.send_keys(zhifumima)

    driver.get_screenshot_as_file("/tmp/PhantomJSPic4")
    os.system("open /tmp/PhantomJSPic4")

    time.sleep(3)

    print("现在在支付宝中确认付款")
    driver.get_screenshot_as_file("/tmp/PhantomJSPic5")
    driver.find_element_by_id('J_newBtn').click()

    os.system("open /tmp/PhantomJSPic5")

    WebDriverWait(driver, 300).until( 
      expected_conditions.url_contains( 
        'standard/lightpay/light_pay_cashier.htm'
      ) 
    )

    tmp=driver.find_element_by_id('pay_password_rsainput')
    tmp.click()
    tmp.send_keys(zhifumima)

    driver.get_screenshot_as_file("/tmp/PhantomJSPic6")

    print("最后确认付款")
    tmp=driver.find_element_by_id('J_authSubmit')
    tmp.click()
Exemplo n.º 34
0
 def loaded(driver):
     is_sync = EC.url_contains(self.path)
     is_rendered = EC.visibility_of_element_located(
         (By.TAG_NAME, 'body'))
     return is_sync(driver) and is_rendered(driver)
Exemplo n.º 35
0
 def submit_search(self):
     self.wait.until(EC.element_to_be_clickable(
         (By.CLASS_NAME, 'mm-btn')
     )).click()
     self.wait.until(EC.url_contains('/search/'))
Exemplo n.º 36
0
def test_search_from_home(live_server, env_browser, search_tests):
    """Test search functionality"""
    browser = env_browser

    # Go to index page
    browser.get(flask.url_for('hepdata_theme.index', _external=True))
    assert (flask.url_for('hepdata_theme.index', _external=True) in
            browser.current_url)

    # Click 'View all'
    search_all_link = browser.find_element_by_css_selector('#latest_records_section').find_element_by_tag_name('a')
    search_all_link.click()
    element = WebDriverWait(browser, 10).until(
        EC.url_contains('search')
    )
    assert (flask.url_for('es_search.search', _external=True) in
            browser.current_url)

    # Check result count
    sleep(1)
    results = browser.find_elements_by_class_name('search-result-item')
    assert(len(results) == 2)

    # Check facet filtering for each facet
    facets = [
        {'class_prefix': 'collaboration', 'exp_filter_count': 2, 'exp_first_result_count': 1},
        {'class_prefix': 'subject_areas', 'exp_filter_count': 1, 'exp_first_result_count': 2},
        {'class_prefix': 'phrases', 'exp_filter_count': 10, 'exp_first_result_count': 1},
        {'class_prefix': 'reactions', 'exp_filter_count': 9, 'exp_first_result_count': 1},
        {'class_prefix': 'observables', 'exp_filter_count': 3, 'exp_first_result_count': 1},
        {'class_prefix': 'cmenergies', 'exp_filter_count': 10, 'exp_first_result_count': None}
    ]

    for facet in facets:
        # Check the number of filters for the facet
        facet_filters = browser.find_elements_by_css_selector('#' + facet['class_prefix'] + '-facet li.list-group-item a')
        assert(len(facet_filters) == facet['exp_filter_count'])

        if len(facet_filters) > 0 and facet['exp_first_result_count'] is not None:
            # Check the number of results for first filter in the facet
            result_count = int(facet_filters[0].find_element_by_class_name('facet-count').text.strip())
            assert(result_count == facet['exp_first_result_count'])

            # Move to the first filter and click
            ActionChains(browser).move_to_element(facet_filters[0])
            facet_filters[0].click()
            assert (flask.url_for('es_search.search', _external=True) in
                    browser.current_url)

            # Check the number of search results matches the number given in the filter
            results = browser.find_elements_by_class_name('search-result-item')
            assert(len(results) == facet['exp_first_result_count'])

            # Go back to the previous search results
            browser.back()

    for search_config in search_tests:
        try:
            # Go to the homepage
            browser.get(flask.url_for('hepdata_theme.index', _external=True))
            assert (flask.url_for('hepdata_theme.index', _external=True) in
                    browser.current_url)

            # Find the search form, input the query and submit
            search_form = browser.find_element_by_class_name('main-search-form')
            search_input = search_form.find_element_by_name('q')

            search_term = search_config['search_term']
            search_input.send_keys(search_term)

            search_form.submit()
            sleep(1)

            assert (flask.url_for('es_search.search', _external=True) in
                    browser.current_url)

            # Check the expected publication appears in the search results
            publication = browser.find_element_by_class_name(search_config['exp_hepdata_id'])
            assert (publication)

            # Check the expected collaboration facets appear in the filters
            collab_facets = browser.find_element_by_css_selector('#collaboration-facet ul.list-group li.list-group-item a')
            assert(collab_facets.text.startswith(search_config['exp_collab_facet']))
            assert(collab_facets.text.endswith('1'))

            # Click on the link to the publication details
            selector = ".{0} .record-header a".format(search_config['exp_hepdata_id'])

            element = WebDriverWait(browser, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, selector))
            )
            element.click()

            assert (flask.url_for('hepdata_records.get_metadata_by_alternative_id', recid=search_config['exp_hepdata_id'],
                                  _external=True) in browser.current_url)
        except Exception as e:
            screenshot_name = "./search-{}.png".format(search_config['exp_hepdata_id'])
            make_screenshot(browser, screenshot_name)
            print('Error occurred on test. Screenshot captured and saved in tmpdir as {}'.format(screenshot_name))
            raise e
Exemplo n.º 37
0
    def test_valid(self):
        get_user_model().objects.create_superuser('tester', '', 'test')
        self.do_login(username='******', password='******')

        WebDriverWait(self.browser, 30).until(
            url_to_be("%s/accounts/profile/" % self.live_server_url),
            'Should redirect to profile page'
        )

        edid_detail_url = \
            "%s/edid/%i/" % (self.live_server_url, self.edid.id)
        edid_update_url = \
            "%s/edid/%i/update/" % (self.live_server_url, self.edid.id)
        edid_revision_url = \
            "%s/edid/%i/revision/" % (self.live_server_url, self.edid.id)
        timing_1_update_url = "%s/edid/%i/standard_timing/%i/update/" % (
            self.live_server_url,
            self.edid.id,
            self.edid.standardtiming_set.all()[0].id
        )

        # Go to timing update page
        self.browser.get(timing_1_update_url)

        # Update timing and submit form
        self.browser.find_element_by_id('id_refresh_rate').clear()
        self.browser.find_element_by_id('id_refresh_rate').send_keys('120')
        self.browser.find_element_by_id('submit-id-submit').click()

        WebDriverWait(self.browser, 30).until(
            url_to_be(edid_update_url),
            'Should redirect to EDID update page'
        )

        # Update EDID and submit form
        self.browser.find_element_by_link_text('Monitor Range Limits').click()
        self.browser.find_element_by_id('id_monitor_range_limits').click()
        self.browser.find_element_by_id('submit-id-submit').click()

        WebDriverWait(self.browser, 30).until(
            url_contains(edid_detail_url),
            'Should redirect to EDID detail page'
        )

        # Check 'Monitor Range Limits' is disabled
        self.assertRaises(
            NoSuchElementException,
            self.browser.find_element_by_id,
            'monitor_range_limits'
        )

        # Go to EDID revisions page
        self.browser.get(edid_revision_url)

        # Revert revision 1
        self.browser.find_element_by_id('revision-1-revert-link').click()

        # Confirm revert action
        self.browser.find_element_by_id('revert-id-revert').submit()

        WebDriverWait(self.browser, 30).until(
            url_contains(edid_detail_url),
            'Should redirect to EDID detail page'
        )

        # Check 'Monitor Range Limits' is enabled
        self.browser.find_element_by_id('monitor_range_limits')
Exemplo n.º 38
0
 def wait_for_url_contains(self, part: str, timeout=None):
     _log.debug("wait for: URL contains part='%s'", part)
     timeout = constants.URL_WAIT_TIMEOUT if timeout is None else timeout
     return self.wait(timeout).until(EC.url_contains(part))
Exemplo n.º 39
0
def goto_shoplist(driver):
    driver.get(URL_LIST)
    print('wait for loading...')
    wait = WebDriverWait(driver, FOREVER)
    wait.until(EC.url_contains(URL_LIST))
    print('open completed.')
Exemplo n.º 40
0
 def search(self):
     self.browser.find_element_by_class_name('search-form').submit()
     self.wait.until(EC.url_contains('/search/'))
Exemplo n.º 41
0
 def wait_for_url(self, url, timeout=_DEFAULT_TIMEOUT):
     self.get_wait(timeout).until(
         ec.url_contains(url),
         message=f"Esperaba la URL {url} y obtuve {self.driver.current_url}"
     )
 def _wait_for_url(self, driver, url_contains):
     return WebDriverWait(driver,
                          self.timeout).until(EC.url_contains(url_contains))
Exemplo n.º 43
0
 def verificar_url(self, urlpart):
     resp = WebDriverWait(self.driver, 10).until(EC.url_contains(urlpart))
     return bool(resp)
Exemplo n.º 44
0
 def wait_for_url(self, url: str) -> Any:
     WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until(
         EC.url_contains(url)
     )
Exemplo n.º 45
0

login_by_username()
enter_username(args.username)
enter_password(args.password)

with open(args.namesfile, 'r') as file:
    for user in file.readlines():
        driver.get("https://www.tinkercad.com/users/" + user)
        try:
            wait.until(EC.element_to_be_clickable((By.LINK_TEXT, args.design)))
            design_link = driver.find_element_by_link_text(args.design)
            design_link.click()

            edit_path = "//*[contains(text(), 'Copy and Tinker')]"
            wait.until(EC.url_contains("things"))
            edit_link = driver.find_element_by_xpath(edit_path)
            edit_link.click()

            wait.until(EC.url_contains("edit"))

            minecraft_path = "/html/body/div[2]/div/div/div[1]/nav/div[2]/div[3]/div[2]/div/a"
            wait.until(EC.element_to_be_clickable((By.XPATH, minecraft_path)))
            minecraft_link = driver.find_element_by_xpath(minecraft_path)
            action = ActionChains(driver)
            action.move_to_element(minecraft_link).click().perform()
            action.move_to_element(minecraft_link).click().perform()

            export_path = "//*[contains(text(), 'Export')]"
            export_button = driver.find_element_by_xpath(
                export_path).find_element_by_xpath("..")
Exemplo n.º 46
0
 def go_to_cart(self):
     self.click(self.CART_LOCATOR)
     self.wait.until(EC.url_contains(self.order_page_url))
Exemplo n.º 47
0
 def login(self):
     driver.get(self.login_url)
     # 确定登录成功
     WebDriverWait(driver, 1000).until(EC.url_contains(self.personal_url))
     print("登录成功!")
     pass
Exemplo n.º 48
0
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

driver.get('http://one2020.xjtu.edu.cn/EIP/user/index.htm')

if driver.current_url == "https://org.xjtu.edu.cn/openplatform/login.html":
  driver.implicitly_wait(0.5)
  driver.find_element_by_class_name("username").send_keys(netid)
  driver.implicitly_wait(0.5)
  driver.find_element_by_class_name("pwd").send_keys(password)
  driver.implicitly_wait(0.5)
  driver.find_element_by_id("account_login").click()

element = WebDriverWait(driver, 10, 0.5).until(EC.url_contains("one2020.xjtu.edu.cn"))
driver.get('http://one2020.xjtu.edu.cn/EIP/weixin/weui/home.html')
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//p[text()='本科生每日健康状况填报']")))
driver.find_element_by_xpath("//p[text()='本科生每日健康状况填报']").click()
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//h3[text()='返校登记后每日健康填报']")))
driver.find_elements_by_xpath("//h3[text()='返校登记后每日健康填报']/following-sibling::a[1]")[0].click()
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请准确填写体温,格式如:36.5']")))
driver.find_elements_by_xpath("//p[text()='绿色']/../..")[0].click()
driver.find_elements_by_xpath("//input[@placeholder='请准确填写体温,格式如:36.5']")[0].send_keys(temperature)
driver.find_elements_by_xpath("//a[text()='下一步(流程)']")[0].click()
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请准确填写体温,格式如:36.5']")))
driver.find_elements_by_xpath("//a[text()='提交']")[0].click()
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[text()='确定']")))
driver.find_elements_by_xpath("//a[text()='确定']")[0].click()
driver.quit()
Exemplo n.º 49
0
def wait_for_page(url):
    wait = WebDriverWait(world.browser, webDriverWaitInSeconds)
    wait.until(EC.url_contains(url))