Python webbrowser.html() Examples

The following are 8 code examples of webbrowser.html(). 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 webbrowser , or try the search function .
Example #1
Source File: proj2_yt_mvp.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def search_ytmov(text):
	ytmov_list = []
	gt2vs.getText2VoiceStream("검색어" + text + "해당하는 유튜브 동영상을 검색중입니다 잠시만 기다려주세요", "./yt_search.wav")
	play_file("./yt_search.wav")
	textToSearch = text
	query = quote(textToSearch)
	url = "https://www.youtube.com/results?search_sort=video_view_count&filters=video%2C+video&search_query=" + query
	response = urllib.request.urlopen(url)
	html = response.read()
	soup = BeautifulSoup(html)

	for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
		temp_str = ('https://www.youtube.com' + vid['href'])
		ytmov_list.append(temp_str)

	print("----------------")
	print(ytmov_list[1]) # Return the most viewed YouTube movie's url
	return ytmov_list[1]

	

#### Execute Browser #### 
Example #2
Source File: proj2_yt_mvp.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def search_ytmov(text):
	ytmov_list = []
	gt2vs.getText2VoiceStream("검색어" + text + "해당하는 유튜브 동영상을 검색중입니다 잠시만 기다려주세요", "./yt_search.wav")
	play_file("./yt_search.wav")
	textToSearch = text
	query = quote(textToSearch)
	url = "https://www.youtube.com/results?search_sort=video_view_count&filters=video%2C+video&search_query=" + query
	response = urllib.request.urlopen(url)
	html = response.read()
	soup = BeautifulSoup(html)

	for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
		temp_str = ('https://www.youtube.com' + vid['href'])
		ytmov_list.append(temp_str)

	print("----------------")
	print(ytmov_list[1]) # Return the most viewed YouTube movie's url
	return ytmov_list[1]

	

#### Execute Browser #### 
Example #3
Source File: terminal.py    From ttrv with MIT License 5 votes vote down vote up
def display(self):
        """
        Use a number of methods to guess if the default webbrowser will open in
        the background as opposed to opening directly in the terminal.
        """

        if self._display is None:
            if sys.platform == 'darwin':
                # OS X won't set $DISPLAY unless xQuartz is installed.
                # If you're using OS X and you want to access a terminal
                # browser, you need to set it manually via $BROWSER.
                # See issue #166
                display = True
            else:
                display = bool(os.environ.get("DISPLAY"))

            # Use the convention defined here to parse $BROWSER
            # https://docs.python.org/2/library/webbrowser.html
            console_browsers = ['www-browser', 'links', 'links2', 'elinks',
                                'lynx', 'w3m']
            if "BROWSER" in os.environ:
                user_browser = os.environ["BROWSER"].split(os.pathsep)[0]
                if user_browser in console_browsers:
                    display = False
            if webbrowser._tryorder:
                if webbrowser._tryorder[0] in console_browsers:
                    display = False
            self._display = display
        return self._display 
Example #4
Source File: terminal.py    From rtv with MIT License 5 votes vote down vote up
def display(self):
        """
        Use a number of methods to guess if the default webbrowser will open in
        the background as opposed to opening directly in the terminal.
        """

        if self._display is None:
            if sys.platform == 'darwin':
                # OS X won't set $DISPLAY unless xQuartz is installed.
                # If you're using OS X and you want to access a terminal
                # browser, you need to set it manually via $BROWSER.
                # See issue #166
                display = True
            else:
                display = bool(os.environ.get("DISPLAY"))

            # Use the convention defined here to parse $BROWSER
            # https://docs.python.org/2/library/webbrowser.html
            console_browsers = ['www-browser', 'links', 'links2', 'elinks',
                                'lynx', 'w3m']
            if "BROWSER" in os.environ:
                user_browser = os.environ["BROWSER"].split(os.pathsep)[0]
                if user_browser in console_browsers:
                    display = False
            if webbrowser._tryorder:
                if webbrowser._tryorder[0] in console_browsers:
                    display = False
            self._display = display
        return self._display 
Example #5
Source File: terminal.py    From ttrv with MIT License 4 votes vote down vote up
def clean(self, string, n_cols=None):
        """
        Required reading!
            http://nedbatchelder.com/text/unipain.html

        Python 2 input string will be a unicode type (unicode code points).
        Curses will accept unicode if all of the points are in the ascii range.
        However, if any of the code points are not valid ascii curses will
        throw a UnicodeEncodeError: 'ascii' codec can't encode character,
        ordinal not in range(128). If we encode the unicode to a utf-8 byte
        string and pass that to curses, it will render correctly.

        Python 3 input string will be a string type (unicode code points).
        Curses will accept that in all cases. However, the n character count in
        addnstr will not be correct. If code points are passed to addnstr,
        curses will treat each code point as one character and will not account
        for wide characters. If utf-8 is passed in, addnstr will treat each
        'byte' as a single character.

        Reddit's api sometimes chokes and double-encodes some html characters
        Praw handles the initial decoding, but we need to do a second pass
        just to make sure. See https://github.com/tildeclub/ttrv/issues/96

        Example:
            & -> returned directly from reddit's api
            &     -> returned after PRAW decodes the html characters
            &         -> returned after our second pass, this is the true value
        """

        if n_cols is not None and n_cols <= 0:
            return ''

        if isinstance(string, six.text_type):
            string = unescape(string)

        if self.config['ascii']:
            if isinstance(string, six.binary_type):
                string = string.decode('utf-8')
            string = string.encode('ascii', 'replace')
            return string[:n_cols] if n_cols else string
        else:
            if n_cols:
                string = textual_width_chop(string, n_cols)
            if isinstance(string, six.text_type):
                string = string.encode('utf-8')
            return string 
Example #6
Source File: terminal.py    From ttrv with MIT License 4 votes vote down vote up
def get_mailcap_entry(self, url):
        """
        Search through the mime handlers list and attempt to find the
        appropriate command to open the provided url with.

        Will raise a MailcapEntryNotFound exception if no valid command exists.

        Params:
            url (text): URL that will be checked

        Returns:
            command (text): The string of the command that should be executed
                in a subprocess to open the resource.
            entry (dict): The full mailcap entry for the corresponding command
        """

        for parser in mime_parsers.parsers:
            if parser.pattern.match(url):
                # modified_url may be the same as the original url, but it
                # could also be updated to point to a different page, or it
                # could refer to the location of a temporary file with the
                # page's downloaded content.
                try:
                    modified_url, content_type = parser.get_mimetype(url)
                except Exception as e:
                    # If Imgur decides to change its html layout, let it fail
                    # silently in the background instead of crashing.
                    _logger.warning('parser %s raised an exception', parser)
                    _logger.exception(e)
                    raise exceptions.MailcapEntryNotFound()
                if not content_type:
                    _logger.info('Content type could not be determined')
                    raise exceptions.MailcapEntryNotFound()
                elif content_type == 'text/html':
                    _logger.info('Content type text/html, deferring to browser')
                    raise exceptions.MailcapEntryNotFound()

                command, entry = mailcap.findmatch(
                    self._mailcap_dict, content_type, filename=modified_url)
                if not entry:
                    _logger.info('Could not find a valid mailcap entry')
                    raise exceptions.MailcapEntryNotFound()

                return command, entry

        # No parsers matched the url
        raise exceptions.MailcapEntryNotFound() 
Example #7
Source File: terminal.py    From rtv with MIT License 4 votes vote down vote up
def clean(self, string, n_cols=None):
        """
        Required reading!
            http://nedbatchelder.com/text/unipain.html

        Python 2 input string will be a unicode type (unicode code points).
        Curses will accept unicode if all of the points are in the ascii range.
        However, if any of the code points are not valid ascii curses will
        throw a UnicodeEncodeError: 'ascii' codec can't encode character,
        ordinal not in range(128). If we encode the unicode to a utf-8 byte
        string and pass that to curses, it will render correctly.

        Python 3 input string will be a string type (unicode code points).
        Curses will accept that in all cases. However, the n character count in
        addnstr will not be correct. If code points are passed to addnstr,
        curses will treat each code point as one character and will not account
        for wide characters. If utf-8 is passed in, addnstr will treat each
        'byte' as a single character.

        Reddit's api sometimes chokes and double-encodes some html characters
        Praw handles the initial decoding, but we need to do a second pass
        just to make sure. See https://github.com/michael-lazar/rtv/issues/96

        Example:
            &amp;amp; -> returned directly from reddit's api
            &amp;     -> returned after PRAW decodes the html characters
            &         -> returned after our second pass, this is the true value
        """

        if n_cols is not None and n_cols <= 0:
            return ''

        if isinstance(string, six.text_type):
            string = unescape(string)

        if self.config['ascii']:
            if isinstance(string, six.binary_type):
                string = string.decode('utf-8')
            string = string.encode('ascii', 'replace')
            return string[:n_cols] if n_cols else string
        else:
            if n_cols:
                string = textual_width_chop(string, n_cols)
            if isinstance(string, six.text_type):
                string = string.encode('utf-8')
            return string 
Example #8
Source File: terminal.py    From rtv with MIT License 4 votes vote down vote up
def get_mailcap_entry(self, url):
        """
        Search through the mime handlers list and attempt to find the
        appropriate command to open the provided url with.

        Will raise a MailcapEntryNotFound exception if no valid command exists.

        Params:
            url (text): URL that will be checked

        Returns:
            command (text): The string of the command that should be executed
                in a subprocess to open the resource.
            entry (dict): The full mailcap entry for the corresponding command
        """

        for parser in mime_parsers.parsers:
            if parser.pattern.match(url):
                # modified_url may be the same as the original url, but it
                # could also be updated to point to a different page, or it
                # could refer to the location of a temporary file with the
                # page's downloaded content.
                try:
                    modified_url, content_type = parser.get_mimetype(url)
                except Exception as e:
                    # If Imgur decides to change its html layout, let it fail
                    # silently in the background instead of crashing.
                    _logger.warning('parser %s raised an exception', parser)
                    _logger.exception(e)
                    raise exceptions.MailcapEntryNotFound()
                if not content_type:
                    _logger.info('Content type could not be determined')
                    raise exceptions.MailcapEntryNotFound()
                elif content_type == 'text/html':
                    _logger.info('Content type text/html, deferring to browser')
                    raise exceptions.MailcapEntryNotFound()

                command, entry = mailcap.findmatch(
                    self._mailcap_dict, content_type, filename=modified_url)
                if not entry:
                    _logger.info('Could not find a valid mailcap entry')
                    raise exceptions.MailcapEntryNotFound()

                return command, entry

        # No parsers matched the url
        raise exceptions.MailcapEntryNotFound()