使用 python 3.8,我想將 URL 的兩個部分合二為一。這是一個例子:
domain = "https://some.domain.ch/myportal#/"
urllib.parse.urljoin(domain, "test1")
這給出了輸出
'https://some.domain.ch/test1'
但我希望輸出
'https://some.domain.ch/myportal#/test1'
詢問只是為了理解。
作為一種解決方法,我將使用
domain "test1"
uj5u.com熱心網友回復:
urllib.parse.urlparse(domain)
ParseResult(scheme='https', netloc='some.domain.ch', path='/myportal', params='', query='', fragment='/')
問題是#您的路徑中有一個,根據隨后的規范RFC-3986,這是不正確的urllib.parse。
有關URL 各部分的圖表,請參見§3 :
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
在§3.3path中定義。你的是,這與規則有關/myportal
path-absolute = "/" [ segment-nz *( "/" segment ) ]
...
segment-nz = 1*pchar
其pchar在§A中定義:
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
...
pct-encoded = "%" HEXDIG HEXDIG
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
...
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / " " / "," / ";" / "="
#不可能,所以pchar就停path在那里。
#如果不需要,請洗掉:
>>> import urllib.parse
>>> urllib.parse.urljoin("https://some.domain.ch/myportal/", "test1")
'https://some.domain.ch/myportal/test1'
或對其進行百分比編碼:
>>> urllib.parse.quote("#")
'#'
>>> urllib.parse.urljoin("https://some.domain.ch/myportal#/", "test1")
# ^^^
'https://some.domain.ch/myportal#/test1'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425889.html
