我有一个字符串:
'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
And I want:
b'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
但是我一直得到以下错误提示:
b'BZh91AY&SYA\\xaf\\x82\\r\\x00\\x00\\x01\\x01\\x80\\x02\\xc0\\x02\\x00 \\x00!\\x9ah3M\\x07<]\\xc9\\x14\\xe1BA\\x06\\xbe\\x084'
上下文
我从网页中获取了一个字符串并将其存储在变量un
中。现在我想使用BZip2进行解压缩:
bz2.decompress(un)
然而,由于un
是一个str
对象,我得到了以下错误:
TypeError: a bytes-like object is required, not 'str'
因此,我需要将
un
转换为类字节对象,而不更改单个反斜杠为转义反斜杠。编辑1: 感谢所有的帮助! @wim我现在明白你的意思了,但是我不知道如何从我的网络爬取方法中检索类字节对象:
r = requests.get('http://www.pythonchallenge.com/pc/def/integrity.html')
doc = html.fromstring(r.content)
comment = doc.xpath('//comment()')[0].text.split('\n')[1:3]
pattern = re.compile("[a-z]{2}: '(.+)'")
un = re.search(pattern, comment[0]).group(1)
我正在使用的包括
requests
、lxml.html
、re
和bz2
。再次说明,我的目标是使用
bz2
解压缩un
,但我在从网页抓取过程中获取bytes-like对象方面遇到了困难。有什么建议吗?
un.encode('raw_unicode_escape')
是可以接受的! - wim