【发布时间】:2016-12-09 18:48:19
【问题描述】:
我有一个网页,其中包含<span class="x"></span> 标签中包含的各种文本 sn-ps。我想生成每个这样的 sn-p 的有序列表。很直接。
皱纹:经常会出现嵌套在外部标签内的额外<span class="x"> 标签,我不在乎。本质上,我想要一个包含至少一个 <span class="x"> 标记内的每个字符串的列表,但是任何其他嵌套的此类标记都应该被忽略和丢弃。
这是一些 HTML 示例:
<p>
Outer text. <span class="x">Inside a single span.</span> Back to outer text once more. <span class="x"><span class="x">Inside two spans</span> or just one</span>. Perhaps a <span class="x">single span contains <span class="x">several</span>
<span class="x">nests</span> <span class="x">within <span class="x">it</span>
</span>!</span>
</p>
<span class="x">Maybe there's a span out here.</span><span class="x">(Or two.)</span>
<p>
<table>
<tr>
<td>
<span class="x">Or <span class="x">in</span><span class="x">here</span></span>.
</td>
</tr>
</table>
</p>
<p>
<span>No.</span> <span>Still no, but<span class="x">yes</span>.</span>
</p>
连同我想要的输出:
[ "Inside a single span.",
"Inside two spans or just one",
"single span contains several nests within it!",
"Maybe there's a span out here.",
"(Or two.)",
"Or inhere",
"yes" ]
我想提请注意此示例的具体功能:
- 最外层跨度可以出现在较大的 HTML 文档中的任何深度。
- 跨度可以任意嵌套深度。 (虽然在实践中我到目前为止还没有发现任何超过 3 或 4 层的实例)
- 相邻的外部跨度之间可能有也可能没有空格;无论哪种方式,我都希望将它们的内容解析为单独的字符串。
- 不需要没有类“x”的跨度标签。
- 相邻的内部标签之间可能有也可能没有空格;我想保持原样。
- 我预计不会有任何
<span class="x">标记包含任何HTML 标记除了 额外嵌套的<span class="x">标记。
我会对 JavaScript + jQuery 解决方案、Python3 + BeautifulSoup 解决方案或其他完全满意的解决方案感到满意,前提是它比其中任何一个都更适合手头的任务。
【问题讨论】:
-
即使没有
x类,你还想要<span>Maybe there's a span out here.</span><span>(Or two.)</span>吗? -
不,我不知道。很好,这是我在示例中遗漏的一个细节。
-
如果你尝试什么我可以帮助你,但我不会为你编写代码。除非你想付钱给我:)
-
我不是在寻找一个完整的解决方案,也许只是一个建议的算法!
-
好的...这里有个建议:$('span').each(function(){someGlobalArray[] = $(this).text();});现在你只需要解决忽略子部分
标签: javascript jquery python web-scraping beautifulsoup