Пример #1
0
def main():
    ''' 
    NOTES: (IMPORTANT)
    
    Using google sign in does not work. I can only think of harvesting cookies by doing a lot of captchas before the launch using .sleep doing captchas on copmenot.com
    if we solve the cpatcha during the process, it will tremendously slow down the cop time
    
    '''

    browser.get(url)
    #browser.execute_script("window.open(url);")

    startInput = input("Start?: ")
    while (startInput != 'start'):
        startInput = input("Start?: ")

    start_time = time.time()

    findItem(keyword, color1, color2)
    browser.execute_script("document.getElementsByName('commit')[0].click()"
                           )  # Clicks on add to cart button
    WebDriverWait(browser, 10).until(
        EC.visibility_of_any_elements_located((By.ID, 'cart')))

    #test which one is faster
    #checkstart = time.time()
    #browser.find_element_by_xpath('//*[@id="cart"]/a[2]').click()
    browser.execute_script(
        "document.getElementsByClassName('button checkout')[0].click()")
    #print("--- %s seconds ---" % (time.time() - checkstart))

    checkout(browser)

    print("--- %s seconds ---" % (time.time() - start_time))  #timer check
Пример #2
0
	def visibility_of_any_elements_located(self, by, arg, driver=None, timeout=30):
		'''
		An expectation for checking that there is at least one element visible on a web page.
		locator is used to find the element returns the list of WebElements once they are located
		@param
			(by, arg) -- locator
			locator is tuple, as follow:
				(By.CLASS_NAME, class name)
				(By.CSS_SELECTOR, css selector)
				(By.ID, id)
				(By.LINK_TEXT, link text)
				(By.NAME, name)
				(By.PARTIAL_LINK_TEXT, partial link text)
				(By.TAG_NAME, tag name)
				(By.XPATH, xpath)
		'''
		driver = driver or self.driver
		
		try:
			
			element = WebDriverWait(driver, timeout).until(
				EC.visibility_of_any_elements_located((by, arg)))
			
			return element

		except Exception as e:
			# print("wait_for_element timeout: ")
			print(str(e))
			return None
Пример #3
0
def first_check(browser, year_ul, year_li):
    xpath = '//*[@id="ddYearStripe"]/div[2]/table/tbody/tr[2]/td[2]/div/div[2]/ul[%s]/li[%s]' % (year_ul, year_li)
    try:
        WebDriverWait(browser, 5).until(EC.visibility_of_any_elements_located((By.XPATH, xpath)))
    except Exception as e:
        time.sleep(2)
    browser.find_element_by_xpath(xpath)
Пример #4
0
 def like_tweets(self, hashtag):
     bot = self.bot
     bot.get('https://twitter.com/search?q=' + hashtag + '&src=typd')
     wait = WebDriverWait(bot, 6)
     time.sleep(3)
     try:
         for i in range(1, 3):
             bot.execute_script(
                 'window.scrollTo(0, document.body.scrollHeight)')
             time.sleep(2)
             tweets = wait.until(
                 EC.visibility_of_any_elements_located(
                     (By.CLASS_NAME, 'tweet')))
             links = [
                 elem.get_attribute('data-permalink-path')
                 for elem in tweets
             ]
             # print(links)
             for link in links:
                 bot.get('https://twitter.com' + link)
                 try:
                     wait.until(
                         EC.element_to_be_clickable(
                             (By.CLASS_NAME, 'HeartAnimation'))).click()
                     print('Liked a tweet')
                     time.sleep(10)
                 except Exception as error:
                     time.sleep(60)
                     print(error)
     except Exception as error:
         # print('Error: Like tweets has encountered an error')
         time.sleep(2)
         print(error)
         bot.quit()
Пример #5
0
def fourth(browser):
    browser.find_element_by_xpath('//*[@id="ddSubmit"]').click()
    try:
        WebDriverWait(browser, 10).until(EC.visibility_of_any_elements_located((By.XPATH, '//*[@id="ddVehicle"]/div[1]/div[2]/div')))
    except Exception as e:
        time.sleep(5)
    return browser
 def findModels100(self, modelType):
     elements = WebDriverWait(self.driver, 3).until(
         EC.visibility_of_any_elements_located((
             By.XPATH,
             "//td//span[@data-uname='lotsearchLotmodel'and contains(text(), '{}')]"
             .format(modelType))))
     return elements
Пример #7
0
def search_min_price(d1, d2):
    path = "https://store.naver.com/flights/v2/results?trip=RT&scity1=%s&ecity1=%s&scity2=%s&ecity2=%s&adult=%s&child=0&infant=0&sdate1=%s.&sdate2=%s.&fareType=Y" % (
        start_airport, end_airport, end_airport, start_airport, adult_count,
        d1, d2)
    driver.get(path)
    try:
        WebDriverWait(driver, 60).until(
            EC.visibility_of_any_elements_located(
                (By.CLASS_NAME, "tit_apply")))
        html = driver.page_source
        soup = BeautifulSoup(html, "html.parser")
        prices = soup.find_all("span", class_="txt_pay")
        driver.get_screenshot_as_file("./dst/success.png")
        price = prices[0]
        price_str = price.get_text(strip="true")
        p = price_str.replace(",", "")
        print(p)
        sql = "INSERT OR IGNORE INTO trips(start_airport, end_airport, price, start_date, end_date) values (?, ?, ?, ?, ?)"
        cur.execute(sql, (start_airport, end_airport, int(p), d1, d2))
        conn.commit()
    except Exception as e:
        if hasattr(e, 'message'):
            print(e.message)
        else:
            print(e)
        driver.get_screenshot_as_file("./dst/fail.png")
Пример #8
0
def get_when_all_visible(driver, locator):
  """Return elements by locator when all of them are visible.
 Args: driver (base.CustomDriver), locator (tuple)
 Return: selenium.webdriver.remote.webelement.WebElements
 """
  return (WebDriverWait(driver, constants.ux.MAX_USER_WAIT_SECONDS).
          until(EC.visibility_of_any_elements_located(locator)))
Пример #9
0
    def __init__(self):
        driver = webdriver.Chrome()
        urls = ''

        with open(self.Input_file, 'r') as f:
            for line in f.read():
                urls += line

        urls = urls.split('\n')
        for url in urls:
            driver.get(url)
            
            self.responses.append(driver.page_source)
            driver.implicitly_wait(3)
            
            try:
                link = driver.find_element_by_xpath("//a[@data-lynx-mode='asynclazy'][1]")
                link.click()
                wait = WebDriverWait(driver,20)
                wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR,"body")))
                self.responses.append(driver.page_source)
            except NoSuchElementException:
                pass
            break
        driver.quit()
Пример #10
0
def open_stock_dialog(driver, stock):
    WebDriverWait(driver, 5).until(
        EC.visibility_of_any_elements_located((
            By.XPATH,
            "//span[contains(@data-dojo-attach-event, 'onOpenDialogClick')]")))
    elem = driver.find_elements_by_xpath(
        "//span[contains(@data-dojo-attach-event, 'onOpenDialogClick')]")
    # try both elements
    try:
        elem[0].click()
    except:
        elem[1].click()
    # Search the stock
    elem = driver.find_element_by_xpath(
        "//input[@placeholder=\"Instrument search\"]")
    # Setting the max length to 100 so the API'll be able to enter long stocks names
    driver.execute_script(
        "arguments[0].setAttribute('maxlength',arguments[1])", elem, 100)
    elem.send_keys(stock)
    # Open its dialog with JS. Selenium couldn't open the dialog itself.
    script_click_xpath(
        driver,
        f"//*[@id='list-results-instruments']//span[contains(@class, 'instrument-name') and .='{stock}']"
    )
    sleep(1)
def readPage():
    
    WebDriverWait(browser, 15).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "k9GMp")))

    # Author name 
    author = browser.find_elements_by_css_selector("h1")[0].text

    informationBar = browser.find_element_by_class_name("k9GMp")

    # Number of posts
    numberOfPost = informationBar.find_elements_by_css_selector("li")[0]
    numberOfPost = int(numberOfPost.find_element_by_css_selector("span>span").text.replace(",",""))
    
    # Number of followers
    numberOfFollowers = informationBar.find_elements_by_css_selector("li")[1]
    try: 
        numberOfFollowers = int(numberOfFollowers.find_element_by_css_selector("span").get_attribute("title").replace(",",""))
    except: 
        numberOfFollowers = int(numberOfFollowers.find_element_by_css_selector("span>span").get_attribute("title").replace(",",""))
    
    # Number of following
    numberOfFollowing = informationBar.find_elements_by_css_selector("li")[2]
    numberOfFollowing = int(numberOfFollowing.find_element_by_css_selector("span").text.replace(",",""))
    
    p = Page(author, numberOfPost, numberOfFollowers, numberOfFollowing)
    pageInJVersion = json.dumps(p.__dict__)
    print pageInJVersion

    if(serverOn):
        connection = httplib.HTTPConnection(host, port)
        connection.request("POST","/api/ig/pages/", pageInJVersion, headers)
        response = connection.getresponse()
        print("Status: {} and reason: {}".format(response.status, response.reason))

    return author
Пример #12
0
 def click_brands_scroll_btn(self):
     """
     Click right scroll button on the slider to switch image,
     :return: object of page
     """
     self.wait.until(EC.visibility_of_any_elements_located(self.slider_scroll_btn))[2].click()
     return self
 def testShouldFailToFindVisibleElementsWhenExplicitWaiting(
         self, driver, pages):
     pages.load("hidden_partially.html")
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(
             EC.visibility_of_any_elements_located(
                 (By.CLASS_NAME, "redbox")))
Пример #14
0
def get_employee_data(driver, employee_id, employee_name, start_day, end_day, month, year):
    URL = 'https://app.joinhomebase.com/timesheets#summary/{0}/{3}-{1}-{4}/{3}-{2}-{4}'.format(
        employee_id, start_day, end_day, month, year)
    driver.get(URL)  # redirects properly

    # Selenium permanently caches all requests made using xpath which means we have to make
    # requests based on EMPLOYEE NAME and not just going through the tbody which makes the
    # next xpath request we sent to Selenium of tbody equal the previous employee's data.
    # That's why we're looking for employee name and going up to the parent instead.
    person_name = WebDriverWait(driver, 20).until(
        EC.visibility_of_any_elements_located((By.PARTIAL_LINK_TEXT, employee_name)))[0]

    # go up to tbody from child
    table = person_name.find_elements_by_xpath('../../..')[0]
    row = table.find_element_by_tag_name("tr")  # list of one item
    cell = row.find_elements_by_tag_name('td')

    for i, area in enumerate(cell):
        # employee work hours are the 5th cell by default, this might be an inconsistent way
        # for getting data though
        if i == 5:
            # Homebase's HTML sucks so it saves the values with a bunch of random whitespace
            # which we want to get rid of
            final_hours = area.get_attribute('innerText').replace(' ', '').strip()

            return final_hours
Пример #15
0
 def navigateToCampaignPage(self):
     try:
         side_menu_close_link = self.driver.find_elements(
             *RealmaxMainPageLocators.side_menu_close_link)
     except NoSuchElementException:
         pass
     if len(side_menu_close_link) > 0:
         pass
     else:
         side_menu_open_link = self.driver.find_element(
             *RealmaxMainPageLocators.side_menu_open_link)
         side_menu_open_link.click()
     WebDriverWait(self.driver, 10).until(
         cond.visibility_of_any_elements_located((
             By.XPATH,
             ".//*[@id=\"sidebar-nav\"]//span[contains(text(),'Dashboard')]"
         )))
     time.sleep(5)
     campaign_link = self.driver.find_element(
         *RealmaxMainPageLocators.campaign_link)
     campaign_link.click()
     time.sleep(2)
     manage_campaign_link = self.driver.find_element(
         *RealmaxMainPageLocators.manage_campaign_link)
     manage_campaign_link.click()
Пример #16
0
 def open_stock_dialog(self, stock):
     """
     Opening stock dialog
     :param stock: Stock (Display name)
     """
     # It may be one of two elements
     WebDriverWait(self.driver, self.timeout / 2).until(
         expected_conditions.visibility_of_any_elements_located((
             By.XPATH,
             "//span[contains(@data-dojo-attach-event, 'onOpenDialogClick')]"
         )))
     elem = self.driver.find_elements_by_xpath(
         "//span[contains(@data-dojo-attach-event, 'onOpenDialogClick')]")
     try:
         elem[0].click()
     except:
         elem[1].click()
     # Search the stock
     elem = self.driver.find_element_by_xpath(
         "//input[@placeholder=\"Instrument search\"]")
     # Setting the max length to 100 so the API'll be able to enter long stocks names
     self.driver.execute_script(
         "arguments[0].setAttribute('maxlength',arguments[1])", elem, 100)
     elem.send_keys(stock)
     # Open its dialog with JS. Selenium couldn't open the dialog itself.
     script_click_xpath(
         self.driver,
         f"//*[@id='list-results-instruments']//span[contains(@class, 'instrument-name') and .='{stock}']"
     )
     if self.mode == Mode.Invest:
         # Sometimes the invest opens the "Limit" tab instead of the "Market Order"
         script_click_xpath(self.driver, "//span[@data-tab='market-order']")
     sleep(self.long_sleep)
Пример #17
0
def make_soup_sportsbetting(url, parse_type, sport):
    selector_tb = "tbody.event"
    xpath_body = "/html/body"

    selector_sport = SB_HTML_TOOLS[sport][0]
    xpath_sport = SB_HTML_TOOLS[sport][1]

    browser = get_chrome_browser()
    browser.get(url)
    body = browser.find_element_by_xpath(xpath_body)

    WebDriverWait(browser, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, selector_sport)))
    browser.find_element_by_css_selector(selector_sport).click()

    WebDriverWait(browser, 10).until(
        EC.visibility_of_element_located((By.XPATH, xpath_sport)))
    browser.find_element_by_xpath(xpath_sport).click()
    time.sleep(1)

    WebDriverWait(browser, 10).until(
        EC.visibility_of_any_elements_located((By.CSS_SELECTOR, selector_tb)))
    html = browser.page_source
    browser.quit()

    soup = BeautifulSoup(html, parse_type)

    return soup
Пример #18
0
    def test_contractor(self, test_setup):
        contractor = wait.until(
            conditions.element_to_be_clickable(
                (By.XPATH, "//*[text()='CONTRACTORS']")))
        contractor.click()

        dropdown_service_type = wait.until(
            conditions.visibility_of_element_located((
                By.CSS_SELECTOR,
                ".ui-multiselect-trigger-icon.ui-clickable.pi.pi-caret-down")))
        driver.find_element_by_css_selector(
            ".ui-multiselect-trigger-icon.ui-clickable.pi.pi-caret-down")
        dropdown_service_type.click()
        ac_checkbox = driver.find_element_by_xpath(
            "//*[text()='Air conditioning']/preceding-sibling::div")
        ac_checkbox.click()
        close_dropdown = driver.find_element_by_css_selector(
            ".ui-multiselect-close.ui-corner-all")
        close_dropdown.click()
        state_dropdown = driver.find_element_by_css_selector(
            ".ui-dropdown-trigger-icon.ui-clickable.pi.pi-caret-down")
        state_dropdown.click()
        arizona = driver.find_element_by_xpath("//span[text()='Arizona']")
        arizona.click()

        not_found_list = wait.until(
            conditions.visibility_of_any_elements_located(
                (By.XPATH, "//*[text()='Contractors not found']")))
        assert len(not_found_list) == 1
Пример #19
0
 def searchContact(self, by, contact_id):
     WebDriverWait(self.driver, 10).until(cond.title_is("Manage contact"))
     if by == 'email':
         email_search_tb = self.driver.find_element(
             *RealmaxContactPageLocators.email_search_tb)
         email_search_tb.send_keys(contact_id)
         time.sleep(2)
         search_btn = self.driver.find_element(
             *RealmaxContactPageLocators.search_btn)
         search_btn.click()
     elif by == 'tag':
         tag_input = self.driver.find_element_by_xpath(
             ".//div[@class='row ap-search']//input[@id='input-auto-complete-tags-2']"
         )
         tag_input.send_keys(contact_id)
         WebDriverWait(self.driver, 10).until(
             cond.visibility_of_any_elements_located((
                 By.XPATH,
                 ".//div[@class='row ap-search']//div[@id='input-auto-complete-tags-2autocomplete-list']//div[contains(.,'"
                 + contact_id + "')]")))
         tag = self.driver.find_element_by_xpath(
             ".//div[@class='row ap-search']//div[@id='input-auto-complete-tags-2autocomplete-list']//div[contains(.,'"
             + contact_id + "')]")
         tag.click()
         time.sleep(2)
         search_btn = self.driver.find_element(
             *RealmaxContactPageLocators.search_btn)
         search_btn.click()
Пример #20
0
def get_when_all_visible(driver, locator):
    """Return elements by locator when all of them are visible.
 Args: driver (base.CustomDriver), locator (tuple)
 Return: selenium.webdriver.remote.webelement.WebElements
 """
    return (WebDriverWait(driver, constants.ux.MAX_USER_WAIT_SECONDS).until(
        EC.visibility_of_any_elements_located(locator)))
    def wait_for_elements_to_be_visible(self, css_locator):
        self.wait_for_loading_widget()

        elements = WebDriverWait(self.driver, 20).until \
            (EC.visibility_of_any_elements_located(
                    (By.CSS_SELECTOR, css_locator)))
        return elements
Пример #22
0
 def _user_setup():
     current_step_sel = 'grow-aui-progress-tracker-step-current'
     if webdriver.find_element_by_class_name(
             current_step_sel).text == 'Welcome':
         _wait_until(
             webdriver,
             ec.element_to_be_clickable(
                 (By.ID, 'grow-intro-video-skip-button')),
             interaction).click()
     if webdriver.find_element_by_class_name(
             current_step_sel).text == 'Upload your photo':
         _wait_until(
             webdriver,
             ec.element_to_be_clickable(
                 (By.CSS_SELECTOR, '.aui-button-link')),
             interaction).click()
     if webdriver.find_element_by_class_name(
             current_step_sel).text == 'Find content':
         _wait_until(
             webdriver,
             ec.visibility_of_any_elements_located(
                 (By.CSS_SELECTOR,
                  '.intro-find-spaces-space>.space-checkbox')),
             interaction)[0].click()
         _wait_until(
             webdriver,
             ec.element_to_be_clickable(
                 (By.CSS_SELECTOR,
                  '.intro-find-spaces-button-continue')),
             interaction).click()
Пример #23
0
 def find_elements(self, loc):
     try:
         # 等待元素可见
         return WebDriverWait(self.driver, 5).until(
             EC.visibility_of_any_elements_located(loc))
     except BaseException:
         print('page {0} does not have locator {1}'.format(self, loc))
Пример #24
0
    def _get_multiple_web_elements(self, wait_state, by_locator, timeout):
        """
        Retrieves the web elements based on the locator string and the wait condition provided\n
        :param wait_state: is a instance of ElementWaitState,
        :param by_locator: locator of the elements to be located
        :param timeout: by default it is set to 20sec or can be supplied
        :return: web_elements
        """
        if wait_state is ElementWaitState.PRESENT_OF_ALL:
            # An expectation for checking that there is at least one element present on a web page.
            # locator is used to find the element returns the list of WebElements once they are located
            self.context.logger.info(
                f'Waiting for the presence of all elements with locator `'
                f'{str(by_locator)}` on the web page.')
            web_elements = (WebDriverWait(self.context.driver, timeout).until(
                EC.presence_of_all_elements_located(by_locator)))
            self.context.logger.info(
                f'Successfully waited for the presence of all elements with locator `'
                f'{str(by_locator)}` on the web page. Evaluate the list of returned web elements'
            )

        elif wait_state is ElementWaitState.VISIBLE_OF_ANY:
            # An expectation for checking that there is at least one element visible on a web page.
            # locator is used to find the element returns the list of WebElements once they are located
            self.context.logger.info(
                f'Waiting for the visibility of any element  with locator `'
                f'{str(by_locator)}` on the web page.')
            web_elements = (WebDriverWait(self.context.driver, timeout).until(
                EC.visibility_of_any_elements_located(by_locator)))
            self.context.logger.info(
                f'Successfully waited for the visibility of any element  with locator `'
                f'{str(by_locator)}` on the web page.')

        elif wait_state is ElementWaitState.VISIBLE_OF_ALL:
            # An expectation for checking that all elements are present on the DOM of a page and visible.
            # Visibility means that the elements are not only displayed
            # but also has a height and width that is greater than 0.
            # locator - used to find the elements returns the list of WebElements once they are located and visible
            self.context.logger.info(
                f'Waiting for the visibility of all elements with locator `'
                f'{str(by_locator)}` on the web page. Evaluate the list of returned web elements'
            )
            web_elements = (WebDriverWait(self.context.driver, timeout).until(
                EC.visibility_of_all_elements_located(by_locator)))
            self.context.logger.info(
                f'Successfully waited for the visibility of all elements '
                f'{str(by_locator)} on the web page. Evaluate the list of returned web elements'
            )
        else:
            try:
                raise Exception(
                    f'Invalid wait state {wait_state} to get multiple elements. '
                    'Please choose an appropriate option!')
            except ValueError:
                self.context.logger.error(
                    f'Invalid wait state {wait_state} to get '
                    'multiple elements. Please choose an appropriate option!')
                raise ValueError
        return web_elements
Пример #25
0
 def fill_in_textareas(self, music, books):
     textarea_list = self.wait.until(
         expected_conditions.visibility_of_any_elements_located(
             JoinLocators.TEXTAREA_LIST))
     music_area = textarea_list[0]
     favorite_books_area = textarea_list[1]
     music_area.send_keys(music)
     favorite_books_area.send_keys(books)
Пример #26
0
 def get_text_message(self):
     self.click_element(
         (By.CSS_SELECTOR, ".button-group button:nth-child(2)"))
     message = WebDriverWait(self.wd, 2).until(
         EC.visibility_of_any_elements_located(
             (By.CSS_SELECTOR, ".alert a")))
     name_card = message[2].get_attribute('innerHTML')
     return name_card
Пример #27
0
 def _validate(self):
     try:
         self.wait.until(
             EC.visibility_of_any_elements_located(
                 (By.CSS_SELECTOR, "div.modal-dialog")))
         return True
     except:
         return False
Пример #28
0
 def are_elements_visible(self, locator, time_waiting_element=0):
     try:
         WebDriverWait(self.driver, time_waiting_element). \
             until(EC.visibility_of_any_elements_located(
             locator))
         return True
     except TimeoutException:
         return False
Пример #29
0
 def find_elements_by_css(self, driver, css):
     try:
         elements = WebDriverWait(driver, TIME_WAIT).until(
             EC.visibility_of_any_elements_located((By.CSS_SELECTOR, css)))
     except Exception as e:
         logging.error(e)
         return None
     return elements
Пример #30
0
def find_elements(element, wait=wait_time):
    try:
        if 'xpath' not in element:
            elem = WebDriverWait(driver, wait).until(
                EC.visibility_of_any_elements_located(
                    (By.CSS_SELECTOR, element)))
        else:
            elem = WebDriverWait(driver, wait).until(
                EC.visibility_of_any_elements_located(
                    (By.XPATH, element.split('=>')[-1])))
        return elem
    except Exception as e:
        err = e
    time.sleep(fail_wait_time)
    allure.attach(driver.get_screenshot_as_png(), '定位错误',
                  allure.attachment_type.PNG)
    raise err
Пример #31
0
 def get_wait_check_page_result(self, locator, timeout=5):
     """页面检查点判断方法"""
     try:
         WebDriverWait(self.driver, timeout, 0.5).until(
             EC.visibility_of_any_elements_located(locator))
         return True
     except:
         return False
Пример #32
0
 def test_search_submit(self):
     """Mobile search form has submit button."""
     self.toogle_menu()
     self.search_input.send_keys('Cate')
     self.submit_search()
     result, *_ = self.wait.until(EC.visibility_of_any_elements_located(
         (By.CLASS_NAME, 'search-result-link')
     ))
     self.assertIn('Cate', result.text)
Пример #33
0
 def test_search_autocomplete(self):
     """Autocomplete in mobile search should work."""
     self.toogle_menu()
     self.search_input.send_keys('Cate')
     suggestions = self.wait.until(EC.visibility_of_any_elements_located(
         (By.CLASS_NAME, 'autocomplete-suggestion')
     ))
     # last autocomplete item has no contains data
     for item in suggestions[:-1]:
         self.assertTrue(item.get_attribute('data-val') == 'Cate')
Пример #34
0
    def testShouldWaitUntilAtLeastOneVisibleElementsIsFoundWhenSearchingForMany(self):
        self._loadPage("hidden_partially")
        add_visible = self.driver.find_element_by_id("addVisible")
        add_hidden = self.driver.find_element_by_id("addHidden")

        add_visible.click()
        add_visible.click()
        add_hidden.click()

        elements = WebDriverWait(self.driver, 2).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "redbox")))
        self.assertTrue(len(elements) == 2)
Пример #35
0
def get_when_all_visible(driver: WebDriver, locator, wait_seconds=1):
    """Return WebElements by locator when all of them are visible.
    Args:

      locator (tuple)
    Returns:
        selenium.webdriver.remote.webelement.WebElements
    """
    return WebDriverWait(
        driver,
        wait_seconds) \
        .until(EC.visibility_of_any_elements_located(locator))
Пример #36
0
def doit():
    fname = "pokemon.txt"
    markerList = setmarkers()
    recentlist = []
    with open(fname) as f:
        content = f.readlines()

    with open("IgnoreList.txt", "a+") as ignore:
        ignorelist = ignore.read().splitlines()

    with open(
        "SeenList" + str(datetime.datetime.today().day) + "-" + str(datetime.datetime.today().month) + ".txt", "a+"
    ) as file:
        seenlist = file.readlines()

    for item in seenlist:
        itemlist = item.split(",")
        if itemlist[3].strip() > str(datetime.datetime.now() - datetime.timedelta(minutes=30)):
            recentlist.append(item)
            # print str(datetime.datetime.now() - datetime.timedelta(minutes=30))
    if apitoken is not None:
        slack = Slacker(apitoken)
    pokemonlist = []

    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = (
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 " "(KHTML, like Gecko) Chrome/15.0.87"
    )

    # for location in latlonlist:
    #     browser.get(base+location)
    for marker in markerList:
        try:
            browser = webdriver.PhantomJS("E:/phantomjs-2.1.1-windows/bin/phantomjs.exe", desired_capabilities=dcap)
            browser.set_window_size(1024, 768)
            browser.get(base + marker.map)
            # browser.get('https://pokevision.com/#/@33.88962827698492,-98.5474169254303')
            if "maintenance" in browser.title.lower():
                raise Warning("Page is down")
            WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".home-map-scan")))
            browser.find_element_by_css_selector(".home-map-scan").click()
            WebDriverWait(browser, 20).until(
                EC.visibility_of_any_elements_located((By.CSS_SELECTOR, ".leaflet-marker-icon"))
            )
            foo = browser.find_elements_by_css_selector(".leaflet-marker-icon")
            print marker.name
            # beautiful soup to strip out needed info.
            for fee in foo:
                flag = False
                boo = fee.get_attribute("src")
                # print boo
                if "marker-icon.png" in boo:
                    marker.location = (int(fee.location["y"]), int(fee.location["x"]))
                else:
                    path = urlparse.urlparse(boo).path
                    key = [x.split(".") for x in os.path.split(path)]

                    temp = Pokemon(
                        (fee.location["y"], fee.location["x"]),
                        content[int(key[1][0]) - 1],
                        marker.location,
                        marker.name,
                    )

                    datenow = str(datetime.datetime.now())

                    for item in recentlist:
                        splititem = item.split(",")
                        if (
                            temp.name.replace("\n", "").strip() == splititem[0].strip()
                            and str(temp.distance).replace("\n", "").strip() == splititem[2].strip()
                        ):
                            flag = True
                    recentlist.append(
                        (temp.name + ", " + temp.marker + ", " + str(temp.distance) + ", " + datenow).replace("\n", "")
                    )
                    if temp.distance < scopedistance:
                        if not flag:
                            # writes to a file so you can see historical data
                            with open(
                                "SeenList"
                                + str(datetime.datetime.today().day)
                                + "-"
                                + str(datetime.datetime.today().month)
                                + ".txt",
                                "a",
                            ) as myfile:
                                writestring = (
                                    temp.name + ", " + temp.marker + ", " + str(temp.distance) + ", " + datenow
                                ).replace("\n", "")
                                myfile.write(writestring + "\n")
                        if key[1][0] not in ignorelist:
                            pokemonlist.append(temp)

            slackmsg = ""
            for pokemon in sorted(pokemonlist):
                # this distance sets how close a pokemon is note that this is based on screen size and not miles
                msg = (pokemon.name + " " + str(math.floor(pokemon.distance))).replace("\n", "")
                print pokemon.name + " " + str(math.floor(pokemon.distance))
                if marker.screamer and apitoken is not None:
                    slackmsg = slackmsg + "\t" + msg + "\n"
            if len(slackmsg) is not 0:
                slack.chat.post_message("#pokebot", marker.name + " :: \n" + slackmsg)
            del pokemonlist[:]
            browser.quit()
        except Exception, e:
            print marker.name + "  " + str(e)
            with open("errorlog.txt", "a+") as error:
                error.writelines(marker.name + "  " + str(e) + " " + str(datetime.datetime.now()))
            browser.quit()
Пример #37
0
 def locate_elements_by_css_selector(self, cssLocator):
     return WebDriverWait(self.driver, self.elementWait).until(
         EC.visibility_of_any_elements_located((By.CSS_SELECTOR, cssLocator)))
Пример #38
0
 def testShouldFailToFindVisibleElementsWhenExplicitWaiting(self, driver, pages):
     pages.load("hidden_partially.html")
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "redbox")))
Пример #39
0
 def testShouldFailToFindVisibleElementsWhenExplicitWaiting(self):
     self._loadPage("hidden_partially")
     with self.assertRaises(TimeoutException):
         WebDriverWait(self.driver, 0.7).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "redbox")))
 def genomic_mapping_facet(self):
     return WebDriverWait(self.browser, self.timeout).until(
         EC.visibility_of_any_elements_located((By.CSS_SELECTOR, '.text-search-facet-values'))
     )[3]
 def expert_databases_facet(self):
     return WebDriverWait(self.browser, self.timeout).until(
         EC.visibility_of_any_elements_located((By.CSS_SELECTOR, '.text-search-facet-values'))
     )[2]
 def facet_links(self):
     return WebDriverWait(self.browser, self.timeout).until(
         EC.visibility_of_any_elements_located((By.CSS_SELECTOR, 'a.text-search-facet-link'))
     )
 def autocomplete_suggestions(self):
     return WebDriverWait(self.browser, self.timeout).until(
         EC.visibility_of_any_elements_located((By.CSS_SELECTOR, ".global-search li.uib-typeahead-match"))
     )