gpt4 book ai didi

post - Python 错误 : Type error: POST data should be bytes; also user-agent issue

转载 作者:行者123 更新时间:2023-12-04 03:01:34 25 4
gpt4 key购买 nike

使用以下代码我收到一个错误:

TypeError: POST data should be bytes or an iterable of bytes. It cannot be str

第二个问题,我不确定我是否正确指定了我的用户代理,这是我的整个用户代理: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4 .当我在脚本中定义用户代理时,我尽了最大努力。
import urllib.parse
import urllib.request

url = 'http://getliberty.org/contact-us/'
user_agent = 'Mozilla/5.0 (compatible; Chrome/22.0.1229.94; Windows NT)'
values = {'Your Name' : 'Horatio',
'Your Email' : '6765Minus4181@gmail.com',
'Subject' : 'Hello',
'Your Message' : 'Cheers'}

headers = {'User-Agent': user_agent }

data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read()

我知道这个类似的问题, TypeError: POST data should be bytes or an iterable of bytes. It cannot be str ,但答案太新了,帮不上忙。

最佳答案

data = urllib.parse.urlencode(values)
type(data) #this returns <class 'str'>. it's a string

urllib 文档说 urllib.request.Request(url, data ...) :

The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. It should be encoded to bytes before being used as the data parameter. etc etc



(强调我的)

所以你有一个看起来正确的字符串,你需要的是编码成字节的字符串。你选择编码。
binary_data = data.encode(encoding)

在上面的行中:编码可以是 'utf-8' 或 'ascii' 或一堆其他东西。选择服务器期望的任何一个。

所以你最终得到的东西看起来像:
data = urllib.parse.urlencode(values)
binary_data = data.encode(encoding)
req = urllib.request.Request(url, binary_data)

关于post - Python 错误 : Type error: POST data should be bytes; also user-agent issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175253/

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