URL打开,解码编码错误TypeError:需要类似字节的对象,而不是'str'

Makis Chance

我正在学习教程和下一段代码:

import urllib.request as url

def getTextWaPo(URL):
    page = url.urlopen(URL).read().decode('utf8')
    soup = BeautifulSoup(page, 'lxml')
    mytext = ' '.join(map(lambda p: p.text, soup.find_all('article')))
    return mytext.encode('ascii', errors='replace').replace("?", " ")

返回:

TypeError: a bytes-like object is required, not 'str'

但是在文档中,我看到encoding是一个字符串方法。那么为什么我需要类似字节的对象呢?如果不是这样,如何删除文本中的特殊字符?

我环顾四周,但是遇到的答案并没有帮助我,或者至少我没有理解。

安德鲁·麦克道威尔

您的问题是替换而不是编码。您正在使用编码将字符串转换为字节格式,然后使用替换字符串而不是字节。

我不确定没有示例URL对其进行测试时会得到什么样的输出,但是请尝试将return语句替换为;

return mytext.encode('ascii', errors='replace').replace(b"?", b" ")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

类型错误:需要类似字节的对象,而不是“str”:即使使用编码

如何删除“TypeError:需要类似字节的对象,而不是“str””

错误:需要一个类似字节的对象,而不是'str'

Python gnupg“类型错误:需要类似字节的对象,而不是'str'”

使用Python 3.5,抛出错误:TypeError:需要一个类似字节的对象,而不是'str'

如何解决Json错误:TypeError:需要一个类似字节的对象,而不是'str'

Python套接字错误TypeError:需要类似字节的对象,而不是带有send函数的'str'

如何解决错误:TypeError:需要类似字节的对象,而不是FLASK-MAIL的“ str”?

TypeError:需要类似字节的对象,而不是 Python 2.7 中的“str”错误

Python错误:TypeError:需要一个类似字节的对象,而不是'str'

TypeError:预期的类似字节的对象,而不是str

需要一个类似字节的对象,而不是“ STR”作为STR打开的JSON文件

TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str'

无法在b64中编码:需要类似字节的对象,而不是'str'

类型错误:需要一个类似字节的对象,不是“str”,但类型显示字节

TypeError:需要一个类似字节的对象,而不是'str''xxx';'xxx'

Python 3-TypeError:需要一个类似字节的对象,而不是'str'

Python 2到3“ TypeError:需要一个类似字节的对象,而不是'str'”

TypeError:需要一个类似字节的对象,而不是'str'–用Python保存JSON数据

Python 3.7 TypeError:需要一个类似字节的对象,而不是'str'

检查“ response.content”中的字符串,引发“ TypeError:需要类似字节的对象,而不是'str'”

子进程“ TypeError:需要一个类似字节的对象,而不是'str'”

python 3.5:“ TypeError:memoryview:需要一个类似字节的对象,而不是'str'”

Python3 TypeError:需要一个类似字节的对象,而不是“str”

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

TypeError:需要一个类似字节的对象,而不是从文件中读取时的“ str”

TypeError:需要一个类似字节的对象,而在尝试写入csv文件时不是'str'

Python3 .replace产生TypeError:需要一个类似字节的对象,而不是'str'