如何在 Python 中构建 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15799696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to build URLs in Python
提问by Sergio Ayestarán
I need to know how to build URLs in python like:
我需要知道如何在 python 中构建 URL,例如:
http://subdomain.domain.com?arg1=someargument&arg2=someotherargument
What library would you recommend to use and why? Is there a "best" choice for this kind of library?
你会推荐使用什么库,为什么?这种图书馆有“最佳”选择吗?
Also, can you provide me with sample code to start with using the library?
另外,您能否向我提供示例代码以开始使用该库?
采纳答案by Senthil Kumaran
回答by chjortlund
I would go for Python's urllib, it's a built-in library.
我会选择 Python 的urllib,它是一个内置库。
# Python 2:
import urllib
# Python 3:
# import urllib.parse
getVars = {'var1': 'some_data', 'var2': 1337}
url = 'http://domain.com/somepage/?'
# Python 2:
print(url + urllib.urlencode(getVars))
# Python 3:
# print(url + urllib.parse.urlencode(getVars))
Output:
输出:
http://domain.com/somepage/?var2=1337&var1=some_data
回答by user2275693
import requests
payload = {'key1':'value1', 'key2':'value2'}
response = requests.get('http://fireoff/getdata', params=payload)
print response.url
回答by Mike K
import urllib
def make_url(base_url , *res, **params):
url = base_url
for r in res:
url = '{}/{}'.format(url, r)
if params:
url = '{}?{}'.format(url, urllib.urlencode(params))
return url
>>>print make_url('http://example.com', 'user', 'ivan', aloholic='true', age=18)
http://example.com/user/ivan?age=18&aloholic=true
回答by Michael Jaison G
Here is an example of using urlparseto generate URLs. This provides the convenience of adding path to the URL without worrying about checking slashes.
这是urlparse用于生成 URL的示例。这提供了向 URL 添加路径的便利,而无需担心检查斜杠。
import urllib
import urlparse
def build_url(baseurl, path, args_dict):
# Returns a list in the structure of urlparse.ParseResult
url_parts = list(urlparse.urlparse(baseurl))
url_parts[2] = path
url_parts[4] = urllib.urlencode(args_dict)
return urlparse.urlunparse(url_parts)
args = {'arg1': 'value1', 'arg2': 'value2'}
# works with double slash scenario
url1 = build_url('http://www.example.com/', '/somepage/index.html', args)
print(url1)
>>> http://www.example.com/somepage/index.html?arg1=value1&arg2=value2
# works without slash
url2 = build_url('http://www.example.com', 'somepage/index.html', args)
print(url2)
>>> http://www.example.com/somepage/index.html?arg1=value1&arg2=value2

