2017-12-27 58 views
-2

我想在HTTP/https後添加www特定的URL。這裏是我的代碼:在http/https中使用urlparse在python中添加www

import urllib 
from urllib.parse import urlunsplit 

def addhttps(url): 
    replaced=urllib.parse.urlsplit(url) 
    if replaced.scheme=='http' or replaced.scheme=='https' or replaced.scheme=='': 
     replaced = replaced._replace(scheme="https") 
    return replaced.geturl() 

def addWWW(url): 
    replaced=urllib.parse.urlsplit(url) 
    if replaced.netloc=='': 
     replaced = replaced._replace(netloc="www") 
    return replaced.geturl() 

s="example.com" 
c=addhttps(s) 
d=addWWW(c) 

print(c) 
print(d) 

我得到我不想輸出:

https:///example.com 
https://www/example.com 

我期待輸出是這樣的:

https://example.com 
https://www.example.com 

感謝提前:)

回答

1

如何使用urlparse(在python2.7中測試)

from urlparse import urlparse 
s="example.com" 
o = urlparse(s) 
print "https://www.{0}".format(o.path) 

回報

https://www.example.com 
+0

謝謝拉克什 –