我尝试使用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 Requests模块以及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
答案 0 :(得分: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
的{{1}} Element
。
答案 1 :(得分:2)
有一次,当我不得不做类似的事情时,我确实喜欢这样:
pp
答案 2 :(得分: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)