实际上,我正在尝试使用Ansible中的Jinja过滤器来解析HTML响应,因为响应中存在一个特定的属性
我能够使用搜索,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>我只想从由" Item2 : Value“注册的HTML响应中获取与Item2相关的”值“。
发布于 2019-05-08 11:04:58
您可以使用xmllint,就像@ can建议的那样,但是您可以使用XPath表达式来查找包含目标值的元素,而不是按索引选择项。例如,要找到包含h3的Item2元素
xmllint --html --xpath '//h3[contains(text(), "Item2")]/text()' data.html这给了我们:
Item2: Value仅从这些值中提取值是微不足道的。我们可以用这样的剧本来包装:
---
- 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您没有在示例HTML中显示它,但是如果这些值包含在<i>元素中,就像在<h3><i>Item2: Value</i></h3>中一样,那么您只需将您的xpath表达式更改为如下所示:
//h3/i[contains(text(), "Item2")]/text()更新
如果输入HTML无效,那么您的选项就会减少,主要是您最初使用的基于正则表达式的解决方案。我可能会把它扔到awk上,就像这样:
- command: >-
awk -F"<>" '/Item2/ {print $4}'
args:
stdin: "{{ webpage.results }}"
register: result考虑到您在问题中提供的示例数据,这将以result.stdout = xxxxx结束。
https://stackoverflow.com/questions/56034199
复制相似问题