【问题标题】:How to split a html page to multiple pages using python and beautiful soup如何使用python和漂亮的汤将一个html页面拆分为多个页面
【发布时间】:2013-01-21 18:11:58
【问题描述】:

我有一个像这样的简单 html 文件。事实上,我从 wiki 页面中提取了它,删除了一些 html 属性并转换为这个简单的 html 页面。

<html>
   <body>
      <h1>draw electronics schematics</h1>
      <h2>first header</h2>
      <p>
         <!-- ..some text images -->
      </p>
      <h3>some header</h3>
      <p>
         <!-- ..some image -->
      </p>
      <p>
         <!-- ..some text -->
      </p>
      <h2>second header</h2>
      <p>
         <!-- ..again some text and images -->
      </p>
   </body>
</html>

我用 python 和这样的美汤阅读了这个 html 文件。

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("test.html"))

pages = []

我想做的是把这个 html 页面分成两部分。第一部分将在第一个标题和第二个标题之间。第二部分将在第二个标题

标签: python html beautifulsoup


【解决方案1】:

查找h2 标签,然后使用.next_sibling 抓取所有内容,直到它成为另一个h2 标签:

soup = BeautifulSoup(open("test.html"))
pages = []
h2tags = soup.find_all('h2')

def next_element(elem):
    while elem is not None:
        # Find next element, skip NavigableString objects
        elem = elem.next_sibling
        if hasattr(elem, 'name'):
            return elem

for h2tag in h2tags:
    page = [str(h2tag)]
    elem = next_element(h2tag)
    while elem and elem.name != 'h2':
        page.append(str(elem))
        elem = next_element(elem)
    pages.append('\n'.join(page))

使用您的示例,这给出了:

>>> pages
['<h2>first header</h2>\n<p>\n<!-- ..some text images -->\n</p>\n<h3>some header</h3>\n<p>\n<!-- ..some image -->\n</p>\n<p>\n<!-- ..some text -->\n</p>', '<h2>second header</h2>\n<p>\n<!-- ..again some text and images -->\n</p>']
>>> print pages[0]
<h2>first header</h2>
<p>
<!-- ..some text images -->
</p>
<h3>some header</h3>
<p>
<!-- ..some image -->
</p>
<p>
<!-- ..some text -->
</p>

【讨论】:

  • 非常好的解决方案。非常感谢! :) 现在我试着了解发生了什么。
  • @Erdem:.next_sibling 属性包括 NavigableString 对象(基本上是元素之间的文本),next_element() 函数会跳过这些对象。否则,它只会添加每个下一个兄弟姐妹,直到您遇到另一个 h2 或用完兄弟姐妹。
  • 谢谢@Martijn。希望我能够使用引导模板创建网页,例如您的网页或 learn.adafruit.com
猜你喜欢
  • 2019-11-05
  • 2017-08-15
  • 2021-11-27
  • 2012-08-01
  • 1970-01-01
  • 2015-01-26
  • 2023-04-01
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多