Python错误:类型错误:POST数据应为字节;也是用户代理问题 [英] Python error: Type error: POST data should be bytes; also user-agent issue

查看:92
本文介绍了Python错误:类型错误:POST数据应为字节;也是用户代理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the following code I received an error:

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.在脚本中定义用户代理时,我尽了全力.

Second concern, I am not sure if I specified my user-agent correctly, here's my user-agent in whole: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4. I gave my best shot as I defined the user-agent in the script.

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()

我知道这个类似的问题,

I am aware of this similar question, TypeError: POST data should be bytes or an iterable of bytes. It cannot be str, but am too new for the answer to be much help.

推荐答案

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

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

The urllib docs say for urllib.request.Request(url, data ...):

urllib.parse.urlencode()函数采用2元组的映射或序列,并以这种格式返回字符串. 在用作数据参数之前,应将其编码为字节.等,等等

(重点是我的)

因此,您有一个看起来正确的字符串,您需要的是将该字符串编码为字节.然后选择编码.

So you have a string that looks right, what you need is that string encoded into bytes. And you choose the encoding.

binary_data = data.encode(encoding)

在上一行中的

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

in the above line: encoding can be 'utf-8' or 'ascii' or a bunch of other things. Pick whichever one the server expects.

所以您最终得到的是这样的东西:

So you end up with something that looks like:

data = urllib.parse.urlencode(values)
binary_data = data.encode(encoding) 
req = urllib.request.Request(url, binary_data)

这篇关于Python错误:类型错误:POST数据应为字节;也是用户代理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆