Created
March 20, 2012 03:08
-
-
Save flavioamieiro/2130649 to your computer and use it in GitHub Desktop.
Script para buscar o título da página e formatar um tweet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
#-*- coding: utf-8 -*- | |
import sys | |
import re | |
import urllib.request | |
from html.parser import HTMLParser | |
def usage(): | |
sys.stderr.write("usage: {0} <url>\n".format(sys.argv[0])) | |
sys.exit(1) | |
try: | |
url = sys.argv[1] | |
except IndexError: | |
usage() | |
title_regex = b'<title.*>(.*?)<\/title>' | |
content = urllib.request.urlopen(url).read() | |
# re.DOTALL makes . match newlines | |
matches = re.search(title_regex, content, re.IGNORECASE | re.DOTALL) | |
title = matches.group(1).decode('utf-8').replace('\n', '').strip() | |
title = HTMLParser().unescape(title) | |
endchar = '\n' if sys.stdout.isatty() else '' | |
sys.stdout.write('{0} - {1}{2}'.format(title, url, endchar)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
urllib.request.urlopen(url).read()
poderia serurllib.urlopen(url).read()
O requests já resolve alguns dos probleminhas, como detetar encoding e tal.