【发布时间】:2022-01-12 20:10:54
【问题描述】:
我在 python 中使用 BeautifulSoup 来解析 Html 文档并将 ruby 和 rt 标签添加到每个字符串中。最近我一直在为个人 IOS 应用程序开发一个类似的项目。我发现 SwiftSoup 很相似,但在解析标签时遇到了问题,我可以使用 BeautifulSoup 很好地完成该标签。在美丽的汤中,我可以得到一个像下面这样的标签
<p id="p6" data-pid="6" data-rel-pid="[41]" class="p6">
<span class="parNum" data-pnum="1"></span>
This is a(<span id="citationsource2"></span><a epub:type="noteref" href="#citation2">link</a>)to some website。
</p>
使用来自 BS4 的 .content 我可以将标签放入这样的数组中
['\n', <span class="parNum" data-pnum="1"></span>, '\n This is a(', <span id="citationsource2"></span>, <a epub:type="noteref" href="#citation2">link</a>, ')to some website。\n ']
在我遍历数组并检查子标签是否有文本或数组中的元素是否是文本元素之后,我只是附加了 ruby 标记。结果是这样的
<p id="p6" data-pid="6" data-rel-pid="[41]" class="p6">
<span class="parNum" data-pnum="1"></span>
<ruby>This<rt>1</rt></ruby><ruby>is<rt>2</rt></ruby> <ruby>a<rt>3</rt></ruby>(<span id="citationsource2"></span><a epub:type="noteref" href="#citation2"><ruby>link<rt>4</rt></ruby></a>)<ruby>to<rt>5</rt></ruby> <ruby>some<rt>6</rt></ruby> <ruby>website<rt>7</rt></ruby>。
</p>
我使用 SwiftSoup 解析文档,因为它没有像 BS4 .content 这样的类似方法
let soup:Document = try! SwiftSoup.parse(html)
let elements:Elements = try! soup.select("p")
for j in try! elements.html(){
print(try! j)
//Doesn't work prints out every single character not every element
}
问题在于它将p标签的全部内容视为一个元素,它不像BS4那样将p标签中的元素分开。我查看了文档,但没有看到任何关于将元素从标签中分离到数组中的内容。
这就是我想用 Swiftsoup 实现的目标
['\n', <span class="parNum" data-pnum="1"></span>, '\n This is a(', <span id="citationsource2"></span>, <a epub:type="noteref" href="#citation2">link</a>, ')to some website。\n ']
但最终将所有内容都作为数组中的一个元素而不是单独的元素。
[<span class="parNum" data-pnum="1"></span>This is a(<span id="citationsource2">
</span> <a epub:type="noteref" href="#citation2">link</a>)to some website.]
有没有什么方法可以使用 swiftsoup 或其他可以实现相同目的的 swift html 解析器来实现这一点?
【问题讨论】:
标签: swift beautifulsoup html-parsing swiftsoup