[英]python 3.5 : “TypeError: memoryview: a bytes-like object is required, not 'str'”
I am using python 3.5.2
and scrapy 1.1.1
. 我正在使用python
3.5.2
和scrapy 1.1.1
。
There is an error when running the code below: 运行以下代码时发生错误:
#-*- coding:utf-8-*-
import random
import base64
class ProxyMiddleware(object):
def process_request(self, request, spider):
proxy = random.choice(PROXIES)
if proxy['user_pass'] is not None:
request.meta['proxy'] = "http://%s" % proxy['ip_port']
encoded_user_pass = base64.encodebytes(proxy['user_pass'])
request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
print("ok!" + proxy['ip_port'])
else:
print("fail!" + proxy['ip_port'])
request.meta['proxy'] = "http://%s" % proxy['ip_port']
error: 错误:
File "C:\Users\dell\AppData\Local\Programs\Python\Python35\lib\base64.py", line 518, in _input_type_check
m = memoryview(s)
TypeError: memoryview: a bytes-like object is required, not 'str'
I think the error is related to this sentence: 我认为错误与这句话有关:
encoded_user_pass = base64.encodebytes(proxy['user_pass'])
But I don't know how to solve it. 但是我不知道如何解决。
Some help please, 请帮忙
thanks in advance! 提前致谢!
Edit: 编辑:
encoded_user_pass = base64.encodebytes(proxy['user_pass'])
was changed to 改为
encoded_user_pass = base64.encodebytes(proxy['user_pass'].encode())
there is another error: 还有另一个错误:
request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
TypeError: Can't convert 'bytes' object to str implicitly
what should I do? 我该怎么办?
Function base64.encodebytes()
is expecting bytes value and it seems like you are providing it a string. 函数
base64.encodebytes()
期望字节值,并且似乎您正在为其提供字符串。
To fix that you can simply encode your string value (encode() function turns your string object into bytes object): 为了解决这个问题,您可以简单地编码您的字符串值(encode()函数将您的字符串对象转换为字节对象):
base64.encodebytes('foo'.encode())
or in your case: 或者您的情况:
encoded_user_pass = base64.encodebytes(proxy['user_pass'].encode())
As the name suggests, base64.encodebytes
encodes bytes , not strings. 顾名思义,
base64.encodebytes
编码字节而不是字符串。 As outlined in the documentation, it requires a bytes-like object (just like the error message also tells you). 如文档中所述,它需要一个类似字节的对象 (就像错误消息也告诉您一样)。
Your proxy['user_pass']
value is a string however. 但是您的
proxy['user_pass']
值是一个字符串。 In order to convert that into bytes, call str.encode
: 为了将其转换为字节,请调用
str.encode
:
encoded_user_pass = base64.encodebytes(proxy['user_pass'].encode())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.