在编码 BeautifulSoup 上执行 replace() 时出现类型错误导致 Python
TypeError while doing replace() on encoded BeautifulSoup result in Python
尝试对通过 Python 中的 BeautifulSoup 库解析 HTML 数据后收到的文本输出进行编码 3. 出现以下错误:
----> gmtext.encode('ascii', errors='replace').replace("?", "")
TypeError: a bytes-like object is required, not 'str'
代码实现如下:
import urllib.request as urllib2
from bs4 import BeautifulSoup
articleURL = "http://digimon.wikia.com/wiki/Guilmon"
page = urllib2.urlopen(articleURL).read().decode('utf8', 'ignore')
soup = BeautifulSoup(page, 'lxml')
gmtext = soup.find('p').text
gmtext.encode('ascii', errors='replace').replace("?", "")
到目前为止,我找到的关于此错误的所有答案都是关于某种文件打开错误。
.replace()
is a string function, but you're calling it after calling .encode()
,
returns "a bytes-like object" 您不能调用 .replace()
。
如果你愿意,你可以像这样在编码之前进行替换:
gmtext.replace("?", "").encode('ascii', errors='replace')
那就可以了。
您可以用字节替换(在字符串前使用 b
),例如:
gmtext.encode('ascii', errors='replace').replace(b"?", b"")
尝试对通过 Python 中的 BeautifulSoup 库解析 HTML 数据后收到的文本输出进行编码 3. 出现以下错误:
----> gmtext.encode('ascii', errors='replace').replace("?", "")
TypeError: a bytes-like object is required, not 'str'
代码实现如下:
import urllib.request as urllib2
from bs4 import BeautifulSoup
articleURL = "http://digimon.wikia.com/wiki/Guilmon"
page = urllib2.urlopen(articleURL).read().decode('utf8', 'ignore')
soup = BeautifulSoup(page, 'lxml')
gmtext = soup.find('p').text
gmtext.encode('ascii', errors='replace').replace("?", "")
到目前为止,我找到的关于此错误的所有答案都是关于某种文件打开错误。
.replace()
is a string function, but you're calling it after calling .encode()
,
returns "a bytes-like object" 您不能调用 .replace()
。
如果你愿意,你可以像这样在编码之前进行替换:
gmtext.replace("?", "").encode('ascii', errors='replace')
那就可以了。
您可以用字节替换(在字符串前使用 b
),例如:
gmtext.encode('ascii', errors='replace').replace(b"?", b"")