首页 > 解决方案 > 解析 xhtml 时出错,因为要上传到网站的字符串中的“<”字符

问题描述

我正在使用 python 使用 requests.put() 方法将字符串上传到网站,但是在尝试将该字符串上传到网站时出现错误。该错误以解析错误的形式出现,其中指出:

Error parsing xhtml: Unexpected character ' ' (code 32) in content after '<' (malformed start element)

我理解为什么它会显示,因为我的字符串中有'<',并且由于这是html代码,解析器正在寻找相应的'>'而不知道这是字符串的一部分。我尝试使用反斜杠 ('<') 和 ('\<') 进行转义,但它不起作用,因为我收到一个语法错误,说明转义字符的使用不正确。

import requests
import json
from requests.auth import HTTPBasicAuth

example_string = '<p><strong>Into managed branch from 2021-3-1 to 2021-5-3</strong></p><table><colgroup><col style=\\"width: 115.0px;\\" /><col style=\\"width: 95.0px;\\" /><col style=\\"width: 58.0px;\\" /><col style=\\"width: 105.0px;\\" /><col style=\\"width: 110.0px;\\" /><col style=\\"width: 215.0px;\\" /><col style=\\"width: 215.0px;\\" /></colgroup><tbody><tr><td><p>This is going < to print</p></td></tr></tbody></table><p class=\\"auto-cursor-target\\"><br /></p>'

headers = {
    'Content-Type': 'application/json',
}

data = '{"id":"534756378","type":"page", "title":"GL_Engine Output","space":{"key":"CSSFW"},"body":{"storage":{"value":"' + example_string + '","representation":"storage"}}, "version":{"number":109}}'
json.loads(data)
print("JSON loads successful")
response = requests.put('https://confluence.ai.com/rest/api/content/534756378', headers=headers, data=data, auth=HTTPBasicAuth('svc-Auto@ai.com', 'AIengineering1@ai'))
print(response)
print(response.json())

请注意,'<' 在我的字符串“This is going < to print”中沿着 example_string 进一步。

标签: pythonhtmlpython-requestshttprequestxhtml

解决方案


尝试用(小于号)替换<符号。&lt;

<p>This is going &lt; to print</p>

浏览器将此HTML 实体呈现为<.


推荐阅读