我需要找到一个库来构建python中的URL,如:
http://subdomain.domain.com?arg1=someargument&arg2=someotherargument
Run Code Online (Sandbox Code Playgroud)
您会建议使用哪个库?为什么?这种图书馆有"最佳"选择吗?
chj*_*und 48
我会选择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))
Run Code Online (Sandbox Code Playgroud)
输出:
http://domain.com/somepage/?var2=1337&var1=some_data
Run Code Online (Sandbox Code Playgroud)
Sen*_*ran 31
urlparse在python标准库中,所有关于构建有效的URL.查看urlparse的文档
Mic*_*n G 10
以下是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
Run Code Online (Sandbox Code Playgroud)
import requests
payload = {'key1':'value1', 'key2':'value2'}
response = requests.get('http://fireoff/getdata', params=payload)
print response.url
Run Code Online (Sandbox Code Playgroud)
打印: http:// fireoff / getdata?key1 = value1&key2 = value2
小智 6
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68035 次 |
| 最近记录: |