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

在尝试使用urllib请求包含中文参数的数据时,遇到了UnicodeEncodeError,错误指出'ascii' codec无法编码某些字符。为了解决这个问题,需要对中文参数进行编码。在程序中加入适当的编码操作后,问题得到解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import urllib.request
import urllib.parse
import string


def get_method_params():

    url = "http://www.baidu.com/s?wd="
    #拼接字符串(汉字)
    #python可以接受的数据
    #https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3

    name = "美女"
    final_url = url+name
    print(final_url)
    #代码发送了请求
    #网址里面包含了汉字;ascii是没有汉字的;url转译
    #将包含汉字的网址进行转译
    encode_new_url = urllib.parse.quote(final_url,safe=string.printable)
    print(encode_new_url)
    # 使用代码发送网络请求
    # response = urllib.request.urlopen(encode_new_url)
    response = urllib.request.urlopen(final_url)
    print(response)
    #读取内容
    data = response.read().decode()
    print(data)
    #保存到本地
    with open("02-encode.html","w",encoding="utf-8")as f:
        f.write(data)
    # UnicodeEncodeError: 'ascii' codec can't encode
    # characters in position 10-11: ordinal not in range(128)
    #python:是解释性语言;解析器只支持 ascii 0 - 127
    #不支持中文

get_method_params()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值