6

このような単純な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>

この html ファイルを python とこのような美しいスープを使用して読み取ります。

from bs4 import BeautifulSoup

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

pages = []

私がやりたいことは、この html ページを 2 つの部分に分割することです。最初の部分は、最初のヘッダーと 2 番目のヘッダーの間にあります。2 番目の部分は、2 番目のヘッダー <h2> タグと </body> タグの間になります。次に、それらをリストに保存したいと思います。ページ。したがって、 <h2> タグに従って、html ページから複数のページを作成できます。

これをどのように行うべきかについてのアイデアはありますか? ありがとう..

4

1 に答える 1

5

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>
于 2013-01-21T18:19:02.330 に答える