URL 编码
最蠢的办法
from urllib.parse import urlencode, urljoin, unquote, quote, quote_plus
s = "主业"
print(s.encode("utf-8"))
print(str(s.encode("utf-8")).strip("b").replace("\\x", "%").upper())
比较好的办法
my_params = {
"username": "用户",
"password": "密码"
}
print(urlencode(my_params))
其实这个方法也不是特别常用,因为requests
模块会自动完成这个过程。
urlencode 操作
url 编解码
有些网站会在
urlencode
之后对参数进行加密,流程如下:密文 = 加密(urlencode 之后的参数) 发送请求(密文)
有些特殊的网站,cookie 的值需要 urlencode;这种 cookie 的一部分值需要 urlencode 的时候,此时我们希望不能只处理一小部分字符串,可以进行如下操作来进行 urlencode:
s = "http://www.baidu.com" print(quote(s)) print(quote_plus(s))
如果你只是需要知道这里解码之后是什么,可以使用工具。
url 拼接
# 当前 url:
url = "http://www.baidu.com"
# xpath提取到的 urlurl1 = "/hhh/ppp"
url2 = "/xxx/yyy"
# url1 + url2
print(urljoin(url, url1))
print(urljoin(url, url2))
评论