Python selenium.common.exceptions.NoSuchElementException() Examples

The following are 30 code examples of selenium.common.exceptions.NoSuchElementException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.common.exceptions , or try the search function .
Example #1
Source File: test_website.py    From bepasty-server with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def setup_class(self):
        """
        Setup: Open a mozilla browser, login
        """
        self.browser = Firefox()
        self.browser.get('http://localhost:5000/')
        token = self.browser.find_element_by_name("token")
        password = "foo"
        # login
        token.send_keys(password)
        token.send_keys(Keys.ENTER)
        time.sleep(.1)
        try:
            self.browser.find_element_by_xpath("//input[@value='Logout']")
        except NoSuchElementException:
            raise ValueError("Can't login!!! Create a user 'foo' with the permissions"
                             "'read' and 'create' in your PERMISSIONS in the config") 
Example #2
Source File: page_objects.py    From poium with Apache License 2.0 6 votes vote down vote up
def __find_element(self, elem):
        """
        Find if the element exists.
        """
        for i in range(self.timeout):
            elems = Browser.driver.find_elements(by=elem[0], value=elem[1])
            if len(elems) == 1:
                logging.info("✅ Find element: {by}={value} ".format(
                    by=elem[0], value=elem[1]))
                break
            elif len(elems) > 1:
                logging.info("❓ Find {n} elements through: {by}={value}".format(
                    n=len(elems), by=elem[0], value=elem[1]))
                break
            else:
                sleep(1)
        else:
            error_msg = "❌ Find 0 elements through: {by}={value}".format(by=elem[0], value=elem[1])
            logging.error(error_msg)
            raise NoSuchElementException(error_msg) 
Example #3
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def get_last_seen(self, name, timeout=10):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)  # we will send the name to the input key box
        last_seen_css_selector = "._315-i"
        start_time = dt.datetime.now()
        try:
            WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.CSS_SELECTOR, last_seen_css_selector)))
            while True:
                last_seen = self.browser.find_element_by_css_selector(last_seen_css_selector).text
                if last_seen and "click here" not in last_seen:
                    return last_seen
                end_time = dt.datetime.now()
                elapsed_time = (end_time-start_time).seconds
                if elapsed_time > 10:
                    return "None"
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException:
            return "None"
        except Exception:
            return "None"

    # This method does not care about anything, it sends message to the currently active chat
    # you can use this method to recursively send the messages to the same person 
Example #4
Source File: linkedin_ads.py    From info-flow-experiments with GNU General Public License v3.0 6 votes vote down vote up
def save_ads_linkedin(self, file_name=None):
    id = self.unit_id
    sys.stdout.write(".")
    sys.stdout.flush()
    self.driver.set_page_load_timeout(60)

    self.search_term()
    time = str(datetime.now())
    lis = self.driver.find_elements_by_css_selector('div#results-container ol.search-results li.mod.result.job')

    for li in lis:
      try:
        company_title = li.find_element_by_css_selector('div.description bdi a').get_attribute('innerHTML')
        location = li.find_element_by_css_selector('dl.demographic dd.separator bdi').get_attribute('innerHTML')
        ad = strip_tags(time+SEPARATOR+company_title+SEPARATOR+'URL'+SEPARATOR+location).encode("utf8")
        self.log('measurement', 'ad', ad)
      except NoSuchElementException:
        pass 
Example #5
Source File: navigation_page.py    From aws-device-farm-appium-python-tests-for-android-sample-app with Apache License 2.0 6 votes vote down vote up
def go_to_category(self, category_name):
        """Clicks appropriate button in the navigation drawer."""
        self.driver.find_element_by_accessibility_id(self.NAV_DRAWER_TOGGLE_ID).click()
        sleep(self.NAV_DRAWER_ANIMATION_DELAY)

        category_element = None
        num_attempts = 0

        while category_element is None and num_attempts < self.MAX_ATTEMPTS:
            try:
                category_element = self.driver.find_element_by_name(category_name)
                num_attempts += 1
            except NoSuchElementException:
                self.scroll_nav_drawer_down()

        category_element.click() 
Example #6
Source File: lagou.py    From python-script with Apache License 2.0 6 votes vote down vote up
def lagou_filter(browser, job_list, company_name, job_filter):
    '''filter by job types'''
    while True:
        lagou_page(browser, job_list, company_name, job_filter)
        #check next page
        try:
            pages = browser.find_element_by_class_name('pages')
            spans = pages.find_elements_by_tag_name('span')
            span = get_next_span(spans)
            if span:
                span.click()
                time.sleep(SLEEPTIME)
            else:
                return
        except NoSuchElementException as _e:
            print(_e)
            return 
Example #7
Source File: ConnectionScraper.py    From scrape-linkedin-selenium with MIT License 6 votes vote down vote up
def scrape_page(self):
        print("SCRAPING PAGE: ", self.page_num)
        self.scroll_to_bottom()
        try:
            next_btn = self.driver.find_element_by_css_selector('button.next')
        except NoSuchElementException:
            next_btn = None
        connections = self.driver.find_elements_by_css_selector(
            '.search-entity')
        results = []
        for conn in connections:
            result = {}
            result['name'] = conn.find_element_by_css_selector(
                '.actor-name').text
            link = conn.find_element_by_css_selector(
                '.search-result__result-link').get_attribute('href')
            user_id = re.search(r'/in/(.*?)/', link).group(1)
            result['id'] = user_id
            results.append(result)
        return bool(next_btn), results 
Example #8
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_wait_until_first_element_is_found_timeout(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.driver.find_element.side_effect = NoSuchElementException('Unknown')
    element_locator = (By.ID, 'element_id')

    start_time = time.time()
    with pytest.raises(TimeoutException) as excinfo:
        utils.wait_until_first_element_is_found([element_locator])
    end_time = time.time()

    assert 'None of the page elements has been found after 10 seconds' in str(excinfo.value)
    # find_element has been called more than one time
    driver_wrapper.driver.find_element.assert_called_with(*element_locator)
    # Execution time must be greater than timeout
    assert end_time - start_time > 10 
Example #9
Source File: webelement.py    From knitter with GNU General Public License v3.0 6 votes vote down vote up
def __wait_for_appearing(self):

        t = 0
        while t < 120:
            t = t + 1

            try:
                elements = Browser.RunningBrowser.find_elements(self.by, self.value)
            except NoSuchElementException:
                logger.step_normal("Element [%s]: NoSuchElementException." % self.__name__)
                elements = []
                continue
            except UnexpectedAlertPresentException:
                logger.step_warning("Element [%s]: UnexpectedAlertPresentException." % self.__name__)

            if len(elements) == 0:
                time.sleep(0.5)
                logger.step_normal("Element [%s]: WaitForAppearing... Wait 1 second, By [%s]" % (self.__name__,
                                                                                                 self.value))
            else:
                logger.step_normal("Element [%s]: Found [%s] Element. Tried [%s] Times." % (self.__name__,
                                                                                            len(elements), t))
                break 
Example #10
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_first_element(self, elements):
        """Try to find sequentially the elements of the list and return the first element found

        :param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
                         sequentially
        :returns: first element found or None
        :rtype: toolium.pageelements.PageElement or tuple
        """
        from toolium.pageelements.page_element import PageElement
        element_found = None
        for element in elements:
            try:
                if isinstance(element, PageElement):
                    element._web_element = None
                    element._find_web_element()
                else:
                    self.driver_wrapper.driver.find_element(*element)
                element_found = element
                break
            except (NoSuchElementException, TypeError):
                pass
        return element_found 
Example #11
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_element(self, element):
        """Tries to find the element, but does not thrown an exception if the element is not found

        :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
        :returns: the web element if it has been found or False
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        from toolium.pageelements.page_element import PageElement
        web_element = False
        try:
            if isinstance(element, PageElement):
                # Use _find_web_element() instead of web_element to avoid logging error message
                element._web_element = None
                element._find_web_element()
                web_element = element._web_element
            elif isinstance(element, tuple):
                web_element = self.driver_wrapper.driver.find_element(*element)
        except NoSuchElementException:
            pass
        return web_element 
Example #12
Source File: webelement.py    From knitter with GNU General Public License v3.0 6 votes vote down vote up
def __wait_for_disappearing(self):

        t = 0
        while t < 120:
            t = t + 1

            try:
                elements = Browser.RunningBrowser.find_elements(self.by, self.value)
            except NoSuchElementException:
                logger.step_normal("Element [%s]: NoSuchElementException." % self.__name__)
                elements = []
                continue
            except UnexpectedAlertPresentException:
                logger.step_warning("Element [%s]: UnexpectedAlertPresentException." % self.__name__)

            if len(elements) == 0:
                return True
            else:
                time.sleep(0.5)
                logger.step_normal("Element [%s]: WairForDisappearing... Found [%s] Element. Tried [%s] Times." %
                                   (self.__name__, len(elements), t))

        return False 
Example #13
Source File: ProfileScraper.py    From scrape-linkedin-selenium with MIT License 5 votes vote down vote up
def get_mutual_connections(self):
        try:
            link = self.driver.find_element_by_partial_link_text(
                'Mutual Connection')
        except NoSuchElementException as e:
            print("NO MUTUAL CONNS")
            return []
        with ConnectionScraper(scraperInstance=self) as cs:
            cs.driver.get(link.get_attribute('href'))
            cs.wait_for_el('.search-s-facet--facetNetwork form button')
            return cs.scrape_all_pages() 
Example #14
Source File: SeleniumTest.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e:
            return False
        return True 
Example #15
Source File: login.py    From yahooquery with MIT License 5 votes vote down vote up
def get_cookies(self):
        try:
            self.driver.execute_script("window.open('{}');".format(
                self.LOGIN_URL))
            self.driver.switch_to.window(self.driver.window_handles[-1])
            self.driver.find_element_by_id('login-username').send_keys(
                self.email)
            self.driver.find_element_by_xpath(
                "//input[@id='login-signin']").click()
            password_element = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.ID, "login-passwd"))
            )
            password_element.send_keys(self.password)
            self.driver.find_element_by_xpath(
                "//button[@id='login-signin']").click()
            try:
                self.driver.find_element_by_link_text('Finance').click()
            except NoSuchElementException:
                self.driver.find_element_by_xpath('//a[@href="https://finance.yahoo.com/"]').click()
            cookies = self.driver.get_cookies()
            crumb = re.findall(
                '"CrumbStore":{"crumb":"(.+?)"', self.driver.page_source)
            if crumb:
                crumb = crumb[0].replace('\\u002F', '/')
            self.driver.quit()
            return {'cookies': cookies, 'crumb': crumb}
        except TimeoutException:
            return "A timeout exception has occured.  Most likely it's due to \
                    invalid login credentials.  Please try again." 
Example #16
Source File: crawler_selenium.py    From Price-monitor with GNU General Public License v3.0 5 votes vote down vote up
def get_huihui_item(self, item_id):
        huihui_info_dict = {"max_price": None, "min_price": None}
        url = 'https://zhushou.huihui.cn/productSense?phu=https://item.jd.com/' + item_id + '.html'
        try:
            self.chrome.get(url)
            # 共30秒
            retry = 15
            while retry:
                try:
                    element = self.chrome.find_element_by_tag_name('body').text
                    if element:
                        logging.info('Found body element: {}'.format(element))
                        break
                    else:
                        logging.info("huihui body元素出现,内容未出现重试2秒")
                        time.sleep(2)
                        retry -= 1
                except NoSuchElementException:
                    time.sleep(2)
                    retry -= 1
                except StaleElementReferenceException:
                    time.sleep(2)
                    retry -= 1
            url_text = self.chrome.find_element_by_tag_name('body').text
            info = json.loads(url_text)
            huihui_info_dict = {"max_price": info['max'], "min_price": info['min']}
            logging.info(huihui_info_dict)
        except decoder.JSONDecodeError as e:
            logging.warning('Crawl failure: {}'.format(e.msg))
        except NoSuchElementException as e:
            logging.warning('Crawl failure: {}'.format(e.msg))
        except TimeoutException as e:
            logging.warning('Crawl failure: {}'.format(e.msg))
        return huihui_info_dict 
Example #17
Source File: crawler.py    From odds-portal-scraper with The Unlicense 5 votes vote down vote up
def go_to_link(self,link):
        """
        returns True if no error
        False whe page not found
        """
        self.driver.get(link)
        try:
            # If no Login button, page not found
            self.driver.find_element_by_css_selector('.button-dark')
        except NoSuchElementException:
            logger.warning('Problem with link, could not find Login button - %s', link)
            return False
        # Workaround for ajax page loading issue
        time.sleep(self.wait_on_page_load)
        return True 
Example #18
Source File: collect.py    From autowebcompat with Mozilla Public License 2.0 5 votes vote down vote up
def get_coordinates(driver, bug_id, browser, seq_no):
    dom_tree = etree.HTML(driver.execute_script('return document.documentElement.outerHTML'))
    dom_element_tree = etree.ElementTree(dom_tree)
    loc_dict = {}
    dom_tree_elements = [elem for elem in dom_tree.iter(tag=etree.Element)]
    web_elements = driver.find_elements_by_css_selector('*')
    dom_xpaths = []

    for element in dom_tree_elements:
        dom_xpaths.append(dom_element_tree.getpath(element))

    for element in web_elements:
        xpath = driver.execute_script(get_xpath_script, element)

        if xpath in dom_xpaths:
            loc_dict[xpath] = element.size
            loc_dict[xpath].update(element.location)
            dom_xpaths.remove(xpath)

    for xpath in dom_xpaths:
        try:
            element = driver.find_element_by_xpath(xpath)
        except NoSuchElementException:
            continue
        loc_dict[xpath] = element.size
        loc_dict[xpath].update(element.location)

    file_name = 'loc_' + utils.create_file_name(bug_id=bug_id, browser=browser, seq_no=seq_no) + '.txt'
    file_name = os.path.join('data', file_name)
    with open(file_name, 'w') as f:
        json.dump(loc_dict, f) 
Example #19
Source File: PyWhatsapp.py    From PyWhatsapp with Apache License 2.0 5 votes vote down vote up
def send_unsaved_contact_message():
    global message
    try:
        time.sleep(7)
        input_box = browser.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
        for ch in message:
            if ch == "\n":
                ActionChains(browser).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
            else:
                input_box.send_keys(ch)
        input_box.send_keys(Keys.ENTER)
        print("Message sent successfuly")
    except NoSuchElementException:
        print("Failed to send message")
        return 
Example #20
Source File: PyWhatsapp.py    From PyWhatsapp with Apache License 2.0 5 votes vote down vote up
def send_message(target):
    global message, wait, browser
    try:
        x_arg = '//span[contains(@title,' + target + ')]'
        ct = 0
        while ct != 10:
            try:
                group_title = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
                group_title.click()
                break
            except:
                ct += 1
                time.sleep(3)
        input_box = browser.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
        for ch in message:
            if ch == "\n":
                ActionChains(browser).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
            else:
                input_box.send_keys(ch)
        input_box.send_keys(Keys.ENTER)
        print("Message sent successfuly")
        time.sleep(1)
    except NoSuchElementException:
        return 
Example #21
Source File: SeleniumHelper.py    From twitter-accounts-creator-bot with MIT License 5 votes vote down vote up
def getElementFrom(self, fromObject, selector):
		try:
			return fromObject.find_element_by_css_selector(selector)
		except NoSuchElementException:
			return None 
Example #22
Source File: test_studio_editable.py    From xblock-utils with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_html_in_help(self):
        """
        If we include HTML in the help text for a field, the HTML should be displayed in the rendered page
        """
        block = self.set_up_root_block()
        try:
            self.browser.find_element_by_class_name('field_help_link')
        except NoSuchElementException:
            self.fail("HTML anchor tag missing from field help text") 
Example #23
Source File: handlers.py    From browsertrix with MIT License 5 votes vote down vote up
def __call__(self, browser, url):
        log_results = browser.visit(self.prefix + url)

        try:
            error = self.get_error(log_results, browser, url)
        except NoSuchElementException:
            # no error
            error = None
        except Exception as e:
            error = {'msg': str(e)}

        results = {'time': str(datetime.utcnow())}

        if error:
            results['error'] = error
            results['archived'] = False
        else:
            results['archived'] = True
            results['actual_url'] = self.get_actual_url(browser)
            self.set_success_results(browser, url, results)

        results['browser_url'] = self.get_browser_url(browser)

        for n in list(log_results.keys()):
            if not self.is_archived_url(n):
                del log_results[n]

        results['log'] = log_results

        return results 
Example #24
Source File: scraper.py    From facebook-scraper-selenium with GNU General Public License v3.0 5 votes vote down vote up
def safe_find_element_by_id(self, elem_id):
        try:
            return self.browser.find_element_by_id(elem_id)
        except NoSuchElementException:
            return None 
Example #25
Source File: page_objects.py    From poium with Apache License 2.0 5 votes vote down vote up
def select_by_index(self, text):
        """
        selenium API
        Select the option at the given index. This is done by examing the "index" attribute of an
           element, and not merely by counting.

           :Args:
            - index - The option at this index will be selected

           throws NoSuchElementException If there is no option with specisied index in SELECT
        """
        select_elem = self.__get_element(self.k, self.v)
        Select(select_elem).select_by_index(text) 
Example #26
Source File: page_objects.py    From poium with Apache License 2.0 5 votes vote down vote up
def select_by_value(self, value):
        """
        selenium API
        Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specisied value in SELECT
        """
        select_elem = self.__get_element(self.k, self.v)
        Select(select_elem).select_by_value(value) 
Example #27
Source File: page_objects.py    From poium with Apache License 2.0 5 votes vote down vote up
def find(self, context):
        try:
            return context.find_elements(*self.locator)
        except NoSuchElementException:
            return [] 
Example #28
Source File: page_objects.py    From poium with Apache License 2.0 5 votes vote down vote up
def get_element(self, context):
        try:
            elem = context.find_element(*self.locator)
        except NoSuchElementException:
            return None
        else:
            try:
                style_red = 'arguments[0].style.border="2px solid red"'
                context.execute_script(style_red, elem)
            except WebDriverException:
                return elem
            return elem 
Example #29
Source File: SeleniumHelper.py    From twitter-accounts-creator-bot with MIT License 5 votes vote down vote up
def getElementsFrom(self, fromObject, selector):
		try:
			return fromObject.find_elements_by_css_selector(selector)
		except NoSuchElementException:
			return None 
Example #30
Source File: page_element.py    From toolium with Apache License 2.0 5 votes vote down vote up
def web_element(self):
        """Find WebElement using element locator

        :returns: web element object
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        try:
            self._find_web_element()
        except NoSuchElementException as exception:
            parent_msg = " and parent locator '{}'".format(self.parent) if self.parent else ''
            msg = "Page element of type '%s' with locator %s%s not found"
            self.logger.error(msg, type(self).__name__, self.locator, parent_msg)
            exception.msg += "\n  {}".format(msg % (type(self).__name__, self.locator, parent_msg))
            raise exception
        return self._web_element