模仿 web URL 对 python 中的汉字进行编码
mimic web URL encode for Chinese character in python
我想模仿URL汉字编码。对于我的用例,我在 URL 中搜索 e-commerce 站点
'https://search.jd.com/Search?keyword={}'.format('ipad')
当我用英文搜索产品时,效果很好。但是,我需要输入中文,我试过了
'https://search.jd.com/Search?keyword={}'.format('耐克t恤')
,在网络选项卡下发现如下编码
https://list.tmall.com/search_product.htm?q=%C4%CD%BF%CBt%D0%F4
所以基本上,我需要将“耐克t恤”之类的输入编码为“%C4%CD%BF%CBt%D0%F4”。我不确定网站使用的是哪种编码?另外,如何将汉字转换成这些编码python?
更新:我检查了 headers 内容编码似乎是 gzip?
使用的编码好像是GB2312
这可以帮助你:
def encodeGB2312(data):
hexData = data.encode(encoding='GB2312').hex().upper()
encoded = '%' + '%'.join(hexData[i:i + 2] for i in range(0, len(hexData), 2))
return encoded
output = encodeGB2312('耐克t恤')
print(output)
url = f'https://list.tmall.com/search_product.htm?q={output}'
print(url)
输出:
%C4%CD%BF%CB%74%D0%F4
https://list.tmall.com/search_product.htm?q=%C4%CD%BF%CB%74%D0%F4
我的代码的唯一问题是它似乎没有 100% 符合您要实现的 link。它将 t
字符转换为 GB2312 编码。虽然它似乎在您的 link 中使用了未编码的 t
字符。虽然它在打开 url.
时似乎仍然有效
编辑:
Vignesh Bayari R 他的 post 以正确(预期)的方式处理 URL。但在这种情况下,我的解决方案也有效。
尝试使用库 urllib.parse
模块。更具体地说,urllib.parse.urlencode()
函数。您可以传递编码(在本例中它似乎是 'gb2312')和一个包含查询参数的字典,以获得您可以直接使用的有效 url 后缀。
在这种情况下,您的代码将类似于:
import urllib.parse
keyword = '耐克t恤'
url = 'https://search.jd.com/Search?{url_suffix}'.format(url_suffix=urllib.parse.urlencode({'keyword': keyword}, encoding='gb2312'))
的更多信息
我想模仿URL汉字编码。对于我的用例,我在 URL 中搜索 e-commerce 站点
'https://search.jd.com/Search?keyword={}'.format('ipad')
当我用英文搜索产品时,效果很好。但是,我需要输入中文,我试过了
'https://search.jd.com/Search?keyword={}'.format('耐克t恤')
,在网络选项卡下发现如下编码
https://list.tmall.com/search_product.htm?q=%C4%CD%BF%CBt%D0%F4
所以基本上,我需要将“耐克t恤”之类的输入编码为“%C4%CD%BF%CBt%D0%F4”。我不确定网站使用的是哪种编码?另外,如何将汉字转换成这些编码python?
更新:我检查了 headers 内容编码似乎是 gzip?
使用的编码好像是GB2312
这可以帮助你:
def encodeGB2312(data):
hexData = data.encode(encoding='GB2312').hex().upper()
encoded = '%' + '%'.join(hexData[i:i + 2] for i in range(0, len(hexData), 2))
return encoded
output = encodeGB2312('耐克t恤')
print(output)
url = f'https://list.tmall.com/search_product.htm?q={output}'
print(url)
输出:
%C4%CD%BF%CB%74%D0%F4
https://list.tmall.com/search_product.htm?q=%C4%CD%BF%CB%74%D0%F4
我的代码的唯一问题是它似乎没有 100% 符合您要实现的 link。它将 t
字符转换为 GB2312 编码。虽然它似乎在您的 link 中使用了未编码的 t
字符。虽然它在打开 url.
编辑:
Vignesh Bayari R 他的 post 以正确(预期)的方式处理 URL。但在这种情况下,我的解决方案也有效。
尝试使用库 urllib.parse
模块。更具体地说,urllib.parse.urlencode()
函数。您可以传递编码(在本例中它似乎是 'gb2312')和一个包含查询参数的字典,以获得您可以直接使用的有效 url 后缀。
在这种情况下,您的代码将类似于:
import urllib.parse
keyword = '耐克t恤'
url = 'https://search.jd.com/Search?{url_suffix}'.format(url_suffix=urllib.parse.urlencode({'keyword': keyword}, encoding='gb2312'))
的更多信息