Posted By

huacnlee on 07/30/08


Tagged

python twitter tinyurl


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

frost_nomak
andrejsbuikis
atr000


Python make url address to Tinyurl


 / Published in: Python
 

URL: http://huacn.blogbus.com/logs/26387436.html

Python make url address to Tinyurl in article content like Twitter message

  1. def tiny_url(url):
  2. """将url转换成tinyurl"""
  3. apiurl = "http://tinyurl.com/api-create.php?url="
  4. tinyurl = urllib.urlopen(apiurl + url).read()
  5. return tinyurl
  6.  
  7. def content_tiny_url(content):
  8. """让消息里面的连接转换成更短的Tinyurl"""
  9.  
  10. regex_url = r'http:\/\/([\w.]+\/?)\S*'
  11. for match in re.finditer(regex_url, content):
  12. url = match.group(0)
  13. content = content.replace(url,tiny_url(url))
  14.  
  15. return content

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: sku on April 4, 2009

don't forget to quote the url:

def tiny_url(url): """tinyurl GET""" apiurl = "http://tinyurl.com/api-create.php?url=" quoted = urllib.quote_plus(url) tinyurl = urllib.urlopen(apiurl + quoted).read() return tinyurl

Posted By: sku on April 4, 2009

Well that didn't work to well. The important thing is quoted = urllib.quote_plus(url) and tinyurl = urllib.urlopen(apiurl + quoted).read(). If you don't quote the url you'll have unexpected results (missing #s, etc).

You need to login to post a comment.