Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

urllib.parse: แยกและรวม URL Components ใน Python

โมดูล urllib.parse จัดการ URL: แยก components, รวมกลับ, encode/decode, query string handling

URL Parsing: urlparse()

>> from urllib.parse import urlparse
>>> url = 'https://mail.google.com/mail/u/0/?tab=rm#inbox'
>>> result = urlparse(url)
ParseResult(scheme='https', netloc='mail.google.com', path='/mail/u/0/',
            params='', query='tab=rm', fragment='inbox')

Result Attributes

AttributeIndexคำอธิบาย
scheme0Protocol (http, https, ftp...)
netloc1Network location (host:port)
path2Hierarchical path
params3Parameters สำหรับ path element สุดท้าย
query4Query string
fragment5Fragment identifier (#...)
username-User name (ถ้ามี)
password-Password (ถ้ามี)
hostname-Host name (lowercase)
port-Port number (int)

รวม URL กลับ: urlunparse()

>> from urllib.parse import urlunparse
>>> urlunparse(result)
'https://mail.google.com/mail/u/0/?tab=rm#inbox'

urlsplit() / urlunsplit() (ไม่แยก params)

>> from urllib.parse import urlsplit, urlunsplit
>>> urlsplit(url)
SplitResult(scheme='https', netloc='mail.google.com', path='/mail/u/0/',
            query='tab=rm', fragment='inbox')
>>> urlunsplit(_)
'https://mail.google.com/mail/u/0/?tab=rm#inbox'

URL Encoding/Decoding

quote() / quote_plus()

>> from urllib.parse import quote, quote_plus
>>> quote('https://example.com/path?query=value')
'https%3A//example.com/path%3Fquery%3Dvalue'

>>> quote_plus('hello world')  # space → +
'hello+world'

unquote() / unquote_plus()

>> from urllib.parse import unquote
>>> unquote('https%3A//example.com/path%3Fquery%3Dvalue')
'https://example.com/path?query=value'

Query String Handling

urlencode() - dict → query string

>> from urllib.parse import urlencode
>>> urlencode({"name": "Rajeev", "salary": 20000})
'name=Rajeev&salary=20000'

>>> urlencode([("key", "val1"), ("key", "val2")])  # multiple values
'key=val1&key=val2'

parse_qs() / parse_qsl() - query string → dict/list

>> from urllib.parse import parse_qs, parse_qsl
>>> parse_qs('name=Rajeev&salary=20000')
{'name': ['Rajeev'], 'salary': ['20000']}

>>> parse_qsl('name=Rajeev&salary=20000')
[('name', 'Rajeev'), ('salary', '20000')]

URL Joining

>> from urllib.parse import urljoin
>>> urljoin('https://example.com/base/', 'path/to/resource')
'https://example.com/base/path/to/resource'
>>> urljoin('https://example.com/base', '/absolute/path')
'https://example.com/absolute/path'

Supported Schemes

file, ftp, gopher, hdl, http, https, imap, mailto, mms, news, nntp, prospero, rsync, rtsp, rtspu, sftp, shttp, sip, sips, snews, svn, svn+ssh, telnet, wais, ws, wss