我有一个字符串:
'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'
但我不断得到:
b'BZh91AY&SYA\\xaf\\x82\\r\\x00\\x00\\x01\\x01\\x80\\x02\\xc0\\x02\\x00 \\x00!\\x9ah3M\\x07<]\\xc9\\x14\\xe1BA\\x06\\xbe\\x084'
Context
我从网页上刮下一个字符串并将其存储在变量中un
。现在我想使用 BZip2 解压缩它:
bz2.decompress(un)
然而,自从un
is a str
对象,我收到此错误:
TypeError: a bytes-like object is required, not 'str'
因此,我需要转换un
到类似字节的对象,而不将单个反斜杠更改为转义的反斜杠。
Edit 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
, and bz2
.
再次强调,我的目标是减压un
using bz2
,但我很难从我的网络抓取过程中获取类似字节的对象。
有什么指点吗?