Python错误:类型错误:POST数据应为字节;还有用户代理问题

2024-04-26 01:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我知道这个类似的问题,但是我太新了,答案没有多大帮助


Tags: 用户importurl代理mozillayourdatabytes
2条回答

您可以尝试使用requests模块作为替代解决方案

import json
import requests

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, 'Content-Type':'application/json' }

data = json.dumps(values)
request = requests.post(url, data=data, headers=headers)

response = request.json()
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)

相关问题 更多 >