我如何/应该使用 Python 将 html 文档分成几个部分? (技术上和逻辑上)

发布于 2024-10-10 07:55:34 字数 508 浏览 0 评论 0原文

我有一个 HTML 文档,我试图将其分成单独的、较小的块。说,取每个< h3> header 并变成自己的单独文件,仅使用该块中编码的 HTML(以及 html、head、body、标签)。

我正在使用Python的Beautiful Soup,我对它很陌生,但似乎很容易用于完成这样的简单任务(有更好的建议,如lxml或Mini-dom吗?)。所以:

1)我该如何去“解析所有<” h3 >s 并将每个变成一个单独的文档'?从指向正确方向的指针到代码片段再到在线文档(Soup 发现的很少)的任何内容都将受到赞赏。

2)从逻辑上讲,找到标签是不够的 - 我需要物理上“剪切它”并将其放入一个单独的文件中(并将其从原始文件中删除)。也许解析文本行而不是节点会更容易(尽管超级难看,从形成的结构中解析原始文本......?)

3)类似相关 - 假设我想从其中删除某个属性一种类型的所有标签(例如,删除所有图像的对齐属性)。这看起来很容易,但我失败了 - 任何帮助将不胜感激! 感谢您的帮助!

I've an HTML document I'm trying to break into separate, smaller chunks. Say, take each < h3 > header and turn into its own separate file, using only the HTML encoded within that chunk (along with html, head, body, tags).

I am using Python's Beautiful Soup which I am new to, but seems easy to use for easy tasks such as this (Any better suggestions like lxml or Mini-dom?). So:

1) How do I go, 'parse all < h3 >s and turn each into a separate doc'? Anything from pointers to the right direction to code snippets to online documentation (found quite little for Soup) will be appreciated.

2) Logically, finding the tag won't be enough - I need to physically 'cut it out' and put it in a separate file (and remove it from original). Perhaps parsing the text lines instead of nodes would be easier (albeit super-ugly, parsing raw text from a formed structure...?)

3) Similarly related - suppose I want to delete a certain attribute from all tags of a type (like, delete the alignment attribute of all images). This seems easy but I've failed - any help will be appreciated!
Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2024-10-17 07:55:34

是的,您使用 BeautifulSoup 或 lxml。两者都有方法来查找要提取的节点。然后,您还可以从节点对象重新创建 HTML,从而将该 HTML 保存到新文件中。

Yes, you use BeautifulSoup or lxml. Both have methods to find the nodes you want to extract. You can then also recreate HTML from the node objects, and hence save that HTML to new files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文