python-urlparse

 

 

http://docs.python.org/2/library/urlparse.html?highlight=urlparse#urlparse

 

主要函數如下:

1。urlparse

 

  1. #!/usr/bin/python 
  2. import urlparse 
  3. webURL = "http://www.google.com/search?hl=en&q=python&btnG=Google+Search" 
  4. #parseTuple = urlparse.urlsplit(webURL) 
  5. parseTuple = urlparse.urlparse(webURL) 
  6. print parseTuple 

輸出如下:

 

  1. ParseResult(scheme='http', netloc='www.google.com', path='/search', params='', query='hl=en&q=python&btnG=Google+Search', fragment=''

我們可以看到輸入爲6個部分;元組 (scheme, netloc, path, parameters, query, fragment)

2. urlparse.urlunparse(parts)

 

  1. #!/usr/bin/python 
  2. import urlparse 
  3. URLschema = "ftp" 
  4. webURL = "http://www.google.com/search?hl=en&q=python&btnG=Google+Search" 
  5. #parseTuple = urlparse.urlsplit(webURL) 
  6. parseTuple = urlparse.urlparse(webURL) 
  7. print parseTuple 
  8. u = urlparse.urlunparse((URLschema,parseTuple.netloc,parseTuple.path,parseTuple.params,parseTuple.query,'')) 
  9. print u 

結果如下:

重新拼合成了一個新的url

 

  1. ParseResult(scheme='http', netloc='www.google.com', path='/search', params='', query='hl=en&q=python&btnG=Google+Search', fragment=''
  2. ftp://www.google.com/search?hl=en&q=python&btnG=Google+Search 

3.

urlparse.urlsplit(urlstring[, scheme[, allow_fragments]])
This function returns a 5-tuple: (addressing scheme, network location, path, query, fragment identifier).

  1. SplitResult(scheme='http', netloc='www.google.com', path='/search', query='hl=en&q=python&btnG=Google+Search', fragment=''

4.urlparse.urljoin(base, url[, allow_fragments])

這個的主要作用是拼接url

 

  1. import urlparse 
  2. #-*- coding:utf-8 -*- 
  3. #測試1 
  4. base_url = "http://motor.blog.51cto.com/blog/addblog.php" 
  5. relative_url = "../blog/test.php" 
  6. abs_url = urlparse.urljoin(base_url, relative_url) 
  7. print abs_url 
  8. #測試2 
  9. base_url_2 = "http://motor.blog.51cto.com/blog/addblog.php" 
  10. relative_url_2 = "test.php" 
  11. abs_url_2 = urlparse.urljoin(base_url_2, relative_url_2) 
  12. print abs_url_2 
  13. #測試3 
  14. base_url_3 = "http://motor.blog.51cto.com/blog/" 
  15. relative_url_3 = "test.php" 
  16. abs_url_3 = urlparse.urljoin(base_url_3, relative_url_3) 
  17. print abs_url_3 
  18. #測試4 
  19. base_url_4 = "http://motor.blog.51cto.com/blog" 
  20. relative_url_4 = "test.php" 
  21. abs_url_4 = urlparse.urljoin(base_url_4, relative_url_4) 
  22. print abs_url_4 

結果如下:

 

  1. http://motor.blog.51cto.com/blog/test.php 
  2. http://motor.blog.51cto.com/blog/test.php 
  3. http://motor.blog.51cto.com/blog/test.php 
  4. http://motor.blog.51cto.com/test.php 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章