1

body在不依赖 Lxml 或 BeautifulSoup 的情况下从 HTML 页面中提取标签内容的好方法是什么?

我正在为 Django 编写一个附加包,对于这么小的任务,我不想在我的插件中添加另一个依赖项。使用我提到的其中一个库真的很容易,但除了那个和正则表达式之外,我想不出另一种方法。

4

1 回答 1

3

这很 hacky,我敢肯定完全脆弱(不考虑<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 回答