1

bodyLxmlやBeautifulSoupに依存せずにHTMLページからタグのコンテンツを抽出する良い方法は何でしょうか?

私はDjangoのアドオンパッケージを書いていますが、そのような小さなタスクのために、アドオンに別の依存関係を追加するのは嫌です。私が言及したライブラリの1つを使用するのは本当に簡単ですが、それと正規表現以外では、別の方法を考えることはできません。

4

1 に答える 1

3

<body>これはかなりハッキーで、完全に壊れやすいと思います(実際のタグ内に表示されることなどは考慮されていません<body>)が、上記のライブラリを絶対に使用できない場合は、おそらくこのようなものですか?

In [7]: s = '<html><head>More stuff</head><body>Text inside of the body</body>Random text</html>'

In [8]: s.split('<body>')[1].split('</body>')[0]
Out[8]: 'Text inside of the body'

そして<body>、実際の体のタグが懸念される場合、この忌まわしきはうまくいくようです:

In [1]: s = '<html><head>More stuff</head><body>Text inside of the body<body>more sample text</body>and then more text and then another<body> and then another </body> and then end</body>Random text</html>'

In [2]: '</body>'.join('<body>'.join(s.split('<body>')[1:]).split('</body>')[:-1])
Out[2]: 'Text inside of the body<body>more sample text</body>and then more text and then another<body> and then another </body> and then end'
于 2012-11-19T15:30:58.697 に答える