urljoin()
方法用处
urljoin()
方法的作用结果是拼接成一个URL
。
urljoin()
方法模板及官方解释
>>> from urllib.parse import urljoin
>>> help(urljoin)
Help on function urljoin in module urllib.parse:
urljoin(base, url, allow_fragments=True)
Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter.
>>>
官方解释:urljoin()是连接一个基本URL和一个可能的相对URL来形成一个绝对URL
。那么,客观来说,base参数所代表的就是基本URL,url代表相对URL,最后的allow_fragments基本上不常用,它是是否忽略锚点的意思
urljoin()
方法举例
from urllib.parse import urljoin
print(urljoin('https://baidu.com','/index.html'))
#运行结果为 https://baidu.com/index.html
上面正确传入了参数,第一个参数是绝对URL
第二个参数是相对URL
,所以结果可以料到。那么,如果没有按规定使用呢?有以下几点规律:
1.传入两个毫不相干,相对完整的URL
:
结果为第二个URL
from urllib.parse import urljoin
print(urljoin('https://haha.com/index.html','https://baidu.com'))
#运行结果为 https://baidu.com
2.传入两个非常缺损的URL
:
from urllib.parse import urljoin
print(urljoin('www.bai.com','/index.html'))
#结果是 /index.html
所以说,最好不要这么做,否则会产生意想不到的结果!!!