4

我正在尝试使用uClassify API根据文本对对象进行分类。要与 API 交互,我需要发出 XML POST 请求,例如:

<?xml version="1.0" encoding="utf-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/RequestSchema" version="1.01">
  <writeCalls writeApiKey="YOUR_WRITE_API_KEY_HERE" classifierName="ManOrWoman">
    <create id="CreateManOrWoman"/>
  </writeCalls>
</uclassify>

我尝试使用 HTTP 请求模块以及 xml.etree.ElementTree 来创建 XML 树,但我得到了左右错误。这是我尝试过的一些代码:

>>> import elementtree.ElementTree as ET
>>> from xml.etree.cElementTree import Element, ElementTree
>>> import requests
>>>
>>> root = ET.Element("uclassify", xlms="http://api.uclassify.com/1/RequestSchema", version="1.01")
>>> head = ET.SubElement(root, "writeCalls", writeApiKey="*************", classifierName="test")
>>> action = ET.SubElement(head, "create", id="CreateTest")
>>> tree = ElementTree(root)
>>>
>>> r = requests.post('http://api.uclassify.com/', tree)
>>> 
>>> ........
>>> TypeError: must be convertible to a buffer, not ElementTree
4

3 回答 3

5

有一次,当我不得不做类似的事情时,我这样做了:

requests.post(url, data=xml_string, headers={'Content-Type':'application/xml; charset=UTF-8'})
于 2015-10-03T12:20:08.617 回答
4

不是一种requests方法,但这是urllib2我的代码库中使用的一个真正简单的食谱:

import urllib2

from elementtree import ElementTree

def post(url, data, contenttype):
    request = urllib2.Request(url, data)
    request.add_header('Content-Type', contenttype)
    response = urllib2.urlopen(request)
    return response.read()

def postxml(url, elem):
    data = ElementTree.tostring(elem, encoding='UTF-8')
    return post(url, data, 'text/xml')

我怀疑您缺少的是tostring用于转换ElementTree Element您命名的root.

于 2012-08-03T19:18:07.127 回答
1

它正在等待一个字符串 XML,尝试这样的事情(使用请求):

input_string_xml = ElementTree.tostring(tree, encoding='utf8', method='xml')
param_data = {'xml': input_xml}
output_xml = requests.post("http://api.uclassify.com/", data=param_data)
于 2013-10-10T23:14:06.413 回答