我实际上是尝试使用Ansible中的Jinja过滤器针对响应中存在的特定属性来解析HTML URI GET响应
我可以使用搜索功能,正则表达式regex_replace标签h3并将标签i标记为'',但不确定如何获取其余的标签,如下所示
- name: HTML output
set_fact: response="{{ webpage.results | map(attribute='content')| select('search', '<h3>')|map('regex_replace', '<h3>(.*)</h3>', '\\1')| select('search', '<i>')| map('regex_replace', '<i>(.*)</i>', '\\1')| list }}"
register: response
with_indexed_items: "{{ groups['host-group-name'] }}"
当前的HTML“响应”格式
<!--
~ Copyright (c) xxxxxx. All rights reserved.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=xxxxxx">
<title>xxxxxxxx</title>
<script type="text/javascript" src="/xxxxxxxx/xxxxxxx" data-xxxx="xxxx|xxxx|xxxx|xx,,|"></script></head>
<body>
<h3>Item1 : <i>xxxxxx</i></h3>
<h3>Item2 : <i>xxxxx</i></h3>
<h3>Item3 : <i>xxxxx</i></h3>
<h3>Item4: <i>${xxxxx}</i></h3>
<h3>Item5 : <i>xxxxxx</i></h3>
</body>
</html>
我正在尝试从ansible剧本显示(或注册)的HTML页面响应中仅获取与Item2相关联的“ Item2:值”
答案 0 :(得分:1)
您可以按照@ceving的建议使用xmllint
,但可以使用XPath表达式查找包含目标值的元素,而不必按索引选择项目。例如,要查找包含h3
的{{1}}元素:
Item2
哪个给了我们
xmllint --html --xpath '//h3[contains(text(), "Item2")]/text()' data.html
从中仅提取值很简单。我们可以将其包装在这样的剧本中:
Item2: Value
您没有在示例HTML中显示它,但是如果值包含在---
- hosts: localhost
gather_facts: false
tasks:
- name: parse html
command: xmllint --html --xpath '//h3[contains(text(), "Item2")]/text()' -
args:
stdin: "{{ webpage.results }}"
register: match
- debug:
var: match.stdout
- set_fact:
result: "{{ match.stdout.split(': ')[1] }}"
- debug:
var: result
中的<i>
元素中,则只需将xpath表达式更改为:>
<h3><i>Item2: Value</i></h3>
更新
如果输入的HTML无效,则选项较少,主要是您最初使用的基于正则表达式的解决方案。我可能会像这样将它扔到//h3/i[contains(text(), "Item2")]/text()
上:
awk
给出问题中给出的示例数据,结果将以- command: >-
awk -F"<>" '/Item2/ {print $4}'
args:
stdin: "{{ webpage.results }}"
register: result
= result.stdout
结束。