python-urlparse

发布时间:2019-08-07 13:52:57编辑:auto阅读(1699)

     

     

    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 

     

关键字

上一篇: Python-wingide

下一篇: python关于Mysql操作