最近在搞爬虫,需要获取URL,但是URL中包含中文,输入浏览器地址栏能进入网页,但是爬虫却找不到。搜索找到了下面两个将中文字符转换为URL地址字符的方法。
1、字典转换为URL字符串-urlencode
from urllib.parse import urlencode
key = urlencode({"key1":"中文1", "key2":"中文2"}) #中文部分也可以使用英文
#最后转换后的形式为:key1=中文1&key2=中文2
#示例
url = https://www.zdic.net/e/sci/index.php?
key = urlencode({"field":"0", "classid":"8", "keyboard":"护国"})
fullURL = url + key # 完整url
#fullURL: https://www.zdic.net/e/sci/index.php?field=0&classid=8&keyboard=%E6%8A%A4%E5%9B%BD
2、单个字符转换为URL字符串-quote
from urllib.parse import quote
key = quote("中文") #中文部分也可以使用英文
#最后转换后的形式为:中文
#示例
url = "https://www.zdic.net/hans/"
key = quote("安土重迁")
fullURL = url + key # 完整url
#fullURL: https://www.zdic.net/hans/%E5%AE%89%E5%9C%9F%E9%87%8D%E8%BF%81
Over!