短URL.py:在Python中,从comand行短取一个长URL

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了短URL.py:在Python中,从comand行短取一个长URL相关的知识,希望对你有一定的参考价值。

  1. #!/usr/bin/env python
  2. #
  3. # shorturl.py
  4. # Shorts a long URL from command line, using ur1.ca.
  5. # Shows original page's title and short url.
  6. #
  7. # ksaver, (at identi.ca); Sep, 2010.
  8. # version 0.2, Mar 2011.
  9. # Requieres BeautifulSoup library in order to work properly:
  10. # http://www.crummy.com/software/BeautifulSoup/
  11. #
  12. # Public Domain Code.
  13.  
  14. import sys
  15. import urllib2
  16.  
  17. from BeautifulSoup import BeautifulSoup
  18. from urllib import urlencode
  19.  
  20. def shorten(longurl):
  21. shortener = 'http://ur1.ca/'
  22. urlparam = {'longurl': longurl}
  23. encparam = urlencode(urlparam)
  24. request = urllib2.Request(shortener, encparam)
  25. htmlpage = urllib2.urlopen(request).read()
  26. htmlsoup = BeautifulSoup(htmlpage)
  27. txtmatch = htmlsoup.p.text.find('http')
  28. shorturl = htmlsoup.p.text[txtmatch:]
  29. return shorturl
  30.  
  31. def main(url):
  32. htmldoc = urllib2.urlopen(url).read()
  33. mysoup = BeautifulSoup(htmldoc)
  34. title = mysoup.title.text
  35. shorturl = shorten(url)
  36.  
  37. print "'%s': %s\n" % (title, shorturl)
  38.  
  39. if __name__ == '__main__':
  40. if len(sys.argv) > 1:
  41. url = sys.argv[1]
  42. else:
  43. url = raw_input("URL to short: ")
  44. main(url)

以上是关于短URL.py:在Python中,从comand行短取一个长URL的主要内容,如果未能解决你的问题,请参考以下文章

Python爬虫实战:利用scrapy,短短50行代码下载整站短视频

python爬虫实战:利用scrapy,短短50行代码下载整站短视频

python url_parse.py

使用python创建web静态网站

Linux comands

即使项目不连续使用Python,如何从长嵌套列表中删除短列表?