本文整理汇总了Python中xml.etree.ElementTree.ParseError方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.ParseError方法的具体用法?Python ElementTree.ParseError怎么用?Python ElementTree.ParseError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.ParseError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_sdptool_output
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def parse_sdptool_output(cls, output:str):
'''Split the string output by sdptool into individual servcie records
and processes them separately.'''
pattern = r'Failed to connect to SDP server on[\da-zA-Z :]*'
pattern = re.compile(pattern)
result = pattern.findall(output)
for i in result:
output = output.replace(i, '')
record_xmls = output.split('<?xml version="1.0" encoding="UTF-8" ?>\n\n')[1:]
print('Number of service records:', len(record_xmls), '\n\n')
for record_xml in record_xmls:
print(blue('Service Record'))
try:
sr = ServiceRecord(record_xml)
sr.pp()
except ElementTree.ParseError as e:
print(record_xml)
print('\n')
示例2: _extract_response_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def _extract_response_xml(self, domain, response):
"""Extract XML content of an HTTP response into dictionary format.
Args:
response: HTML Response objects
Returns:
A dictionary: {alexa-ranking key : alexa-ranking value}.
"""
attributes = {}
alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
try:
xml_root = ET.fromstring(response._content)
for xml_child in xml_root.findall('SD//'):
if xml_child.tag in alexa_keys and \
alexa_keys[xml_child.tag] in xml_child.attrib:
attributes[xml_child.tag.lower(
)] = xml_child.attrib[alexa_keys[xml_child.tag]]
except ParseError:
# Skip ill-formatted XML and return no Alexa attributes
pass
attributes['domain'] = domain
return {'attributes': attributes}
示例3: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def __init__(self, response, _message=None):
status = response.status
reason = response.reason
body = response.body.read()
try:
detail = XML(body).findtext("./messages/msg")
except ParseError as err:
detail = body
message = "HTTP %d %s%s" % (
status, reason, "" if detail is None else " -- %s" % detail)
Exception.__init__(self, _message or message)
self.status = status
self.reason = reason
self.headers = response.headers
self.body = body
self._response = response
示例4: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def __init__(self, response, _message=None):
status = response.status
reason = response.reason
body = (response.body.read()).decode()
try:
detail = XML(body).findtext("./messages/msg")
except ParseError as err:
detail = body
message = "HTTP %d %s%s" % (
status, reason, "" if detail is None else " -- %s" % detail)
Exception.__init__(self, _message or message)
self.status = status
self.reason = reason
self.headers = response.headers
self.body = body
self._response = response
示例5: calendar_data
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def calendar_data(request):
"""
AJAX JSON results for the calendar (rendered by dashboard.views.calendar)
"""
try:
st = iso8601.parse_date(request.GET['start'])
en = iso8601.parse_date(request.GET['end'])
except (KeyError, ValueError, iso8601.ParseError):
return NotFoundResponse(request, errormsg="Bad request")
user = get_object_or_404(Person, userid=request.user.username)
local_tz = pytz.timezone(settings.TIME_ZONE)
start = st - datetime.timedelta(days=1)
end = en + datetime.timedelta(days=1)
resp = HttpResponse(content_type="application/json")
events = _calendar_event_data(user, start, end, local_tz, dt_string=True, colour=True,
due_before=datetime.timedelta(minutes=1), due_after=datetime.timedelta(minutes=30))
json.dump(list(events), resp, indent=1)
return resp
示例6: parse_replicas_from_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def parse_replicas_from_file(path):
"""
Parses the output of list_replicas from a json or metalink file
into a dictionary. Metalink parsing is tried first and if it fails
it tries to parse json.
:param path: the path to the input file
:returns: a list with a dictionary for each file
"""
with open(path) as fp:
try:
root = ElementTree.parse(fp).getroot()
return parse_replicas_metalink(root)
except ElementTree.ParseError as xml_err:
try:
return json.load(fp)
except ValueError as json_err:
raise MetalinkJsonParsingError(path, xml_err, json_err)
示例7: parse_replicas_from_string
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def parse_replicas_from_string(string):
"""
Parses the output of list_replicas from a json or metalink string
into a dictionary. Metalink parsing is tried first and if it fails
it tries to parse json.
:param string: the string to parse
:returns: a list with a dictionary for each file
"""
try:
root = ElementTree.fromstring(string)
return parse_replicas_metalink(root)
except ElementTree.ParseError as xml_err:
try:
return json.loads(string)
except ValueError as json_err:
raise MetalinkJsonParsingError(string, xml_err, json_err)
示例8: parse_table_definition_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def parse_table_definition_file(file):
"""
Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition
"""
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
handle_error("File '%s' does not exist.", file)
try:
tableGenFile = ElementTree.ElementTree().parse(file)
except OSError as e:
handle_error("Could not read result file %s: %s", file, e)
except ElementTree.ParseError as e:
handle_error("Table file %s is invalid: %s", file, e)
if "table" != tableGenFile.tag:
handle_error(
"Table file %s is invalid: It's root element is not named 'table'.", file
)
return tableGenFile
示例9: _scanDir
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def _scanDir(self, workspace, dir, extra):
self.__dir = dir
try:
info = ElementTree.fromstring(await check_output(
["svn", "info", "--xml", dir],
cwd=workspace, universal_newlines=True))
self.__url = info.find('entry/url').text
self.__revision = int(info.find('entry').get('revision'))
self.__repoRoot = info.find('entry/repository/root').text
self.__repoUuid = info.find('entry/repository/uuid').text
status = await check_output(["svn", "status", dir],
cwd=workspace, universal_newlines=True)
self.__dirty = status != ""
except subprocess.CalledProcessError as e:
raise BuildError("Svn audit failed: " + str(e))
except OSError as e:
raise BuildError("Error calling svn: " + str(e))
except ElementTree.ParseError as e:
raise BuildError("Invalid XML received from svn")
示例10: error
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def error(xml):
"""
Test error handling.
>>> issubclass(ET.ParseError, SyntaxError)
True
>>> error("foo").position
(1, 0)
>>> error("<tag>&foo;</tag>").position
(1, 5)
>>> error("foobar<").position
(1, 6)
"""
try:
ET.XML(xml)
except ET.ParseError:
return sys.exc_value
示例11: check_encoding
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def check_encoding(encoding):
"""
>>> check_encoding("ascii")
>>> check_encoding("us-ascii")
>>> check_encoding("iso-8859-1")
>>> check_encoding("iso-8859-15")
>>> check_encoding("cp437")
>>> check_encoding("mac-roman")
>>> check_encoding("gbk")
Traceback (most recent call last):
ValueError: multi-byte encodings are not supported
>>> check_encoding("cp037")
Traceback (most recent call last):
ParseError: unknown encoding: line 1, column 30
"""
ET.XML("<?xml version='1.0' encoding='%s'?><xml />" % encoding)
示例12: decode_sentinelhub_err_msg
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def decode_sentinelhub_err_msg(response):
""" Decodes error message from Sentinel Hub service
:param response: Sentinel Hub service response
:type response: requests.Response
:return: An error message
:rtype: str
"""
try:
server_message = []
for elem in decode_data(response.content, MimeType.XML):
if 'ServiceException' in elem.tag or 'Message' in elem.tag:
server_message.append(elem.text.strip('\n\t '))
return ''.join(server_message)
except ElementTree.ParseError:
return response.text
示例13: check_addon_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def check_addon_xml(report: Report, addon_path: str, parsed_xml, folder_id_mismatch: bool):
"""Check whether the addon.xml present in the addon is parseable or not
:addon_path: path to the addon
:parsed_xml: parsed tree for xml file
:folder_id_mismatch: whether to allow folder and id mismatch
"""
addon_xml_path = os.path.join(addon_path, "addon.xml")
try:
handle_files.addon_file_exists(report, addon_path, r"addon\.xml")
report.add(Record(INFORMATION, "Created by %s" %
parsed_xml.attrib.get("provider-name")))
addon_xml_matches_folder(report, addon_path, parsed_xml, folder_id_mismatch)
except ET.ParseError:
report.add(Record(PROBLEM, "Addon xml not valid, check xml. %s" %
relative_path(addon_xml_path)))
return parsed_xml
示例14: connect_to_catalog
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def connect_to_catalog(self):
self.catalog = TDSCatalog(self.catalog_url)
self.fm_models = TDSCatalog(
self.catalog.catalog_refs[self.model_type].href)
self.fm_models_list = sorted(list(self.fm_models.catalog_refs.keys()))
try:
model_url = self.fm_models.catalog_refs[self.model_name].href
except ParseError:
raise ParseError(self.model_name + ' model may be unavailable.')
try:
self.model = TDSCatalog(model_url)
except HTTPError:
try:
self.model = TDSCatalog(model_url)
except HTTPError:
raise HTTPError(self.model_name + ' model may be unavailable.')
self.datasets_list = list(self.model.datasets.keys())
self.set_dataset()
self.connected = True
示例15: _decode_data
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ParseError [as 别名]
def _decode_data(self, entry):
"""Decode data field (password or comments)."""
key = entry.get('type', 'password')
key = 'comments' if key == 'note' else key
data = entry.pop('data', '')
if isinstance(data, int):
return key, ''
data = self._decode(data)
if key == 'comments':
if data:
try:
tree = ElementTree.XML(data)
except ElementTree.ParseError:
return key, ''
found = tree.find('.//string')
if found is None:
return key, ''
return key, found.text
return key, ''
return key, data