Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Urlparse module (python module)

Shulou Source: shulou.com Published: 2022-06-01 04:17:36 09月24日 Update

I. brief introduction of urlparse module

The urlparse module mainly splits the url into six parts and returns tuples. And the split part can be reorganized into a url. The main functions are urljoin, urlsplit, urlunsplit, urlparse and so on.

Second, the use of urljoin function

Urljoin mainly splices URL, which takes base as its base address, and then combines with the relative address in url to form an absolute URL address. The function urljoin is particularly useful when dealing with several files in the same location by appending a new file name to the URL base address. It is important to note that if the base address does not end with a character /, then the rightmost part of the URL base address will be replaced by this relative path. If you want to keep the end directory in this path, make sure that the URL base address ends with a character /.

Enter the code:

The import urlparse#urljoin function is the urljoin = urlparse.urljoin ('http://www.sina.cn/cc','file/down.php')print urljoinurljoin1 = urlparse.urljoin (' http://www.sina.cn/cc/','file/down.php')print urljoin1) that combines the domain name and the relative path

The result of running the code:

C:\ Python27\ python.exe C:/Users/Lee/Desktop/d/PycharmProjects/untitled/test.py

Http://www.sina.cn/file/down.php

Http://www.sina.cn/cc/file/down.php

Third, the use of urlparse function and urlsplit function

The main purpose is to analyze the urlstring and return a tuple containing five string items: protocol, location, path, query, fragment. When allow_fragments is False, the item after the tuple is always empty, regardless of whether there is a fragment in the urlstring or not, the item is omitted. Urlsplit () is similar to urlparse ()

Enter the code:

Import urlparse

Url = 'http://www.baidu.com/good/index.php?id=18'

# urlsplit function divides a url check into the corresponding part

Result = urlparse.urlsplit (url)

Print result

# display protocol

Print result.scheme

# display domain name

Print result.netloc

# display relative paths

Print result.path

# display query parameters

Print result.query

The result of running the code:

C:\ Python27\ python.exe C:/Users/Lee/Desktop/d/PycharmProjects/untitled/test.py

SplitResult (scheme='http', netloc='www.baidu.com', path='/good/index.php', query='id=18', fragment='')

Http

Www.baidu.com

/ good/index.php

Id=18

Tags: Function base base address code path part character project module location address domain name file fragment result query input run almost parameter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft Linux OPPO Reno MySQL