html - 处理两个父母之间的文本
问题描述
我有以下 html 文本,其中“tr”的数量是动态的:
<tr>
<td>Dec 1, 2019 11:12 PM</td>
<td>some text1</td>
<td>some text2</td>
<td>some text3</td>
<td>
<input type=button value="Add" id="add" onCLick="add(12345)" data-toggle="modal" data-target="#add" />
</td>
<td></td>
</tr>
<tr>
<td>Dec 5, 2019 4:33 PM</td>
<td>some text1</td>
<td>some text2</td>
<td>some text3</td>
<td>
<input type=button value="Add" id="add" onCLick="add(12345)" data-toggle="modal" data-target="#add" />
</td>
<td></td>
</tr>
<tr>
<td>Dec 9, 2019 1:06 PM</td>
<td>some text1</td>
<td>some text2</td>
<td>some text3</td>
<td>
<input type=button value="Add" id="add" onCLick="add(12345)" data-toggle="modal" data-target="#add" />
</td>
<td></td>
</tr>
我想得到以下结果:
Dec 1, 2019 11:12 PM | some text1 | some text2 | some text3
Dec 5, 2019 4:33 PM | some text1 | some text2 | some text3
Dec 9, 2019 1:06 PM | some text1 | some text2 | some text3
我尝试使用 sed 分组:
sed '/^<tr>/d;:a;N;/^<\/tr>/M!s/\n/ /;ta;P;d'
但当然它不起作用。任何建议如何处理?
解决方案
除非您想要一个快速而肮脏的解决方案,否则解析 html 应该使用 html 解析器完成,如评论中所述。
例如,使用 python:
import bs4 # bs4 stands for beautifulsoup, a html parser
import csv
# I open both input and output file
with open(<input>) as myinput, open(<output>, "w") as myoutput:
# I parse the html
soup = bs4.BeautifulSoup(myinput, 'html.parser')
# I set the delimiter for the csv
csvwriter = csv.writer(myoutput, delimiter="|")
# For each tr tag
for tr in soup.find_all('tr'):
# Here I create a list that contains all text from td
rows = [td.text for td in tr.find_all('td')]
# I write the 4th first values as a csv row
csvwriter.writerow(rows[:4])
现在,如果您不相信这个不错的解决方案,让我们看一下使用 awk 的快速而肮脏的解决方案:
awk '
# I define here input and output delimiters
BEGIN{FS="<|>"; OFS=" | "}
# I store info in array td_info
/<td>/{td_info[++counter]=$3}
# I print the info I need and clean td_info array and counter
/<\/tr>/{
print td_info[1], td_info[2], td_info[3], td_info[4]
counter=0
delete td_info
}
' <input.html>
输出 :
Dec 1, 2019 11:12 PM | some text1 | some text2 | some text3
Dec 5, 2019 4:33 PM | some text1 | some text2 | some text3
Dec 9, 2019 1:06 PM | some text1 | some text2 | some text3
推荐阅读
- jquery - 如何避免 ajax 多次发送到 woocommerce 中的服务器?
- node.js - Node.js 新日期不反映来自 .env 的时区 TZ var
- python-3.x - 数据框和系列之间按行按元素划分
- java - 将 Beam JDBC IO 与 Cassandra 连接
- python - 无法在 mac 上导入 gi 模块 python 3.6
- javascript - 如何在 ag 网格(角度)中处理嵌套的对象数组
- c# - 遍历数组并检查艺术家是否与用户输入的艺术家匹配,然后显示歌曲的详细信息
- android - 在运行时动态替换 Lottie 动画中的 Image
- javascript - 显示或隐藏 div,取决于复选框
- python - 在函数之间传递多个变量-Python