gpt4 book ai didi

python-3.x - python 3.5 : "TypeError: memoryview: a bytes-like object is required, not ' str'"

转载 作者:行者123 更新时间:2023-12-03 15:51:00 31 4
gpt4 key购买 nike

我正在使用 python 3.5.2和爬虫 1.1.1 .

运行以下代码时出现错误:

#-*- 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']

错误:
  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'

我认为错误与这句话有关:
encoded_user_pass = base64.encodebytes(proxy['user_pass'])

但我不知道如何解决它。
请一些帮助,
提前致谢!

编辑:
encoded_user_pass = base64.encodebytes(proxy['user_pass'])

改为
encoded_user_pass = base64.encodebytes(proxy['user_pass'].encode())

还有一个错误:
    request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
TypeError: Can't convert 'bytes' object to str implicitly

我该怎么办?

最佳答案

功能 base64.encodebytes()期待字节值,似乎您正在为它提供一个字符串。

要解决这个问题,您可以简单地对字符串值进行编码(encode() 函数将您的字符串对象转换为字节对象):

base64.encodebytes('foo'.encode())

或者在你的情况下:
encoded_user_pass = base64.encodebytes(proxy['user_pass'].encode())

关于python-3.x - python 3.5 : "TypeError: memoryview: a bytes-like object is required, not ' str'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38553705/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com