Python爬虫:urlencode带参url的拼接

如果连接直接这样写,看上去很直观,不过参数替换不是很方便,而且看着不舒服

https://www.mysite.com/?sortField=%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD&pageIndex=3&pageSize=20

可以使用如下方式美化代码

from urllib import urlencode

url = "https://www.mysite.com/"

parameter = {
    "pageSize": 20,
    "sortField": "人工智能",
    "pageIndex": 3
}

data = urlencode(parameter)

print(url + "?" + data)
# https://www.mysite.com/?sortField=%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD&pageIndex=3&pageSize=20

当然可以封装成小函数,以便复用

from urllib import urlencode


def get_url(url, parameters):
    """
    拼接url与所带参数
    :param url: {str} 链接
    :param parameters: {dict} 参数
    :return: {str} 拼接后的url
    """
    data = urlencode(parameters)

    return url + "?" + data


if __name__ == '__main__':

    url = "https://www.mysite.com/"

    parameters = {
        "pageSize": 20,
        "sortField": "人工智能",
        "pageIndex": 3
    }

    print(get_url(url, parameters))
# https://www.mysite.com/?sortField=%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD&pageIndex=3&pageSize=20

参考:
Python2和Python3中urllib库中urlencode的使用注意事项

你可能感兴趣的:(python)