如何快速将html表数据解析为字符串数组? [英] How to parse html table data to array of string in swift?
问题描述
我正在开发一个iOS应用,该应用需要解析带有swiftsoup库的链接中的HTML.我已经做了.但是它将所有表数据显示为字符串.我需要获取单独的数据,这些数据应该存储在单独的数组中.
I'm developing an iOS app in which I need to parse HTML from a link with the swiftsoup library. I have done it. But it shows all the table data as a string. I need to get separate data which should be stored in separate arrays.
这是桌子:
<table width="880" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="81"><strong>Trip Name </strong></td>
<td width="159"><div align="center"><strong>Starting Time from Campus </strong></div></td>
<td width="186"><div align="center"><strong>Starting Spot & Time </strong></div></td>
<td width="444"><strong>Remarks</strong></td>
</tr>
<tr>
<td><div align="center">Normal-1</div></td>
<td><div align="center">6:30 AM </div></td>
<td>Rupsha, 7:20 AM </td>
<td>Will back via Royalmore & Ferighat </td>
</tr>
<tr>
<td><div align="center">Normal-1</div></td>
<td><div align="center">6:45 AM </div></td>
<td>Moylapota, 7:25 AM </td>
<td>Will back via Shibbari - Sonadangha </td>
</tr>
</table>
我已经解析了一个字符串,例如 行程名称从校园出发点开始的时间时间备注正常-1
And I have done to parse a string like Trip Name Starting Time from Campus Starting Spot & Time Remarks Normal-1
我使用的代码:
let doc: Document = try! SwiftSoup.parse(html)
for element: Element in try! doc.select("table[width=880]")
{
let linkText : String = try! element.text();
print(linkText)
}
Normal-1,6:30 AM,7:20AM,将通过Royalmore& Ferighat将存储4个单独的数组.
The Normal-1, 6:30AM, 7:20AM , Will back via Royalmore & Ferighat will be stored 4 separate array.
推荐答案
我不确定您要将其存储为每行一个数组还是每个列一个数组.这是您以每行一个数组的方式存储它的方法.使用map
或其他数组转换将其转换为所需的样式:
I'm not sure whether you want to store it as one-array-per-row or one-array-per-column. Here's how you can store it in one-array-per-row style. Use map
or other array transformations to convert it ot the style you want:
var tableContent = [[String]]()
let document = try! SwiftSoup.parse(html)
for row in try! document.select("table[width=\"880\"] tr") {
var rowContent = [String]()
for col in try! row.select("td") {
let colContent = try! col.text()
rowContent.append(colContent)
}
tableContent.append(rowContent)
}
print(tableContent)
(如果您在生产环境中执行此操作,请正确处理错误,而不要处理所有try!
的错误)
(If you do this in production, handle errors properly instead of all those try!
)
这篇关于如何快速将html表数据解析为字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!