UnicodeEncodeError: 'ascii' codec can't encode characters in position: ordinal not in range(128)

叁歲伎倆 2022-02-03 11:21 323阅读 0赞
  1. import urllib.request
  2. import urllib.parse
  3. import string
  4. def get_method_params():
  5. url = "http://www.baidu.com/s?wd="
  6. #拼接字符串(汉字)
  7. #python可以接受的数据
  8. #https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3
  9. name = "美女"
  10. final_url = url+name
  11. print(final_url)
  12. #代码发送了请求
  13. #网址里面包含了汉字;ascii是没有汉字的;url转译
  14. #将包含汉字的网址进行转译
  15. encode_new_url = urllib.parse.quote(final_url,safe=string.printable)
  16. print(encode_new_url)
  17. # 使用代码发送网络请求
  18. # response = urllib.request.urlopen(encode_new_url)
  19. response = urllib.request.urlopen(final_url)
  20. print(response)
  21. #读取内容
  22. data = response.read().decode()
  23. print(data)
  24. #保存到本地
  25. with open("02-encode.html","w",encoding="utf-8")as f:
  26. f.write(data)
  27. # UnicodeEncodeError: 'ascii' codec can't encode
  28. # characters in position 10-11: ordinal not in range(128)
  29. #python:是解释性语言;解析器只支持 ascii 0 - 127
  30. #不支持中文
  31. get_method_params()

在这里插入图片描述
使用urllib请求数据,携带中文参数,出现如上错误。
解决办法:

  1. import urllib.parse
  2. import string
  3. #将包含汉字的网址进行转译
  4. encode_new_url = urllib.parse.quote(final_url,safe=string.printable)
  5. print(encode_new_url)
  6. # 使用代码发送网络请求
  7. response = urllib.request.urlopen(encode_new_url)

加入以上代码即可,使用urllib将中文参数编码。
最终程序如下:

  1. import urllib.request
  2. import urllib.parse
  3. import string
  4. def get_method_params():
  5. url = "http://www.baidu.com/s?wd="
  6. #拼接字符串(汉字)
  7. #python可以接受的数据
  8. #https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3
  9. name = "美女"
  10. final_url = url+name
  11. print(final_url)
  12. #代码发送了请求
  13. #网址里面包含了汉字;ascii是没有汉字的;url转译
  14. #将包含汉字的网址进行转译
  15. encode_new_url = urllib.parse.quote(final_url,safe=string.printable)
  16. print(encode_new_url)
  17. # 使用代码发送网络请求
  18. response = urllib.request.urlopen(encode_new_url)
  19. # response = urllib.request.urlopen(final_url)
  20. print(response)
  21. #读取内容
  22. data = response.read().decode()
  23. print(data)
  24. #保存到本地
  25. with open("02-encode.html","w",encoding="utf-8")as f:
  26. f.write(data)
  27. # UnicodeEncodeError: 'ascii' codec can't encode
  28. # characters in position 10-11: ordinal not in range(128)
  29. #python:是解释性语言;解析器只支持 ascii 0 - 127
  30. #不支持中文
  31. get_method_params()

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读