正在分析HTML标记和尾部信息



OK我一直在尝试解析一个

html标签,其中包含其他标签和文本

例如

如果我有这个html(是的,我知道使用<b><i>是不好的,但它只是一个简单的例子)

<p> <b> 1 </b> Apple <b> 2 </b> <i> Orange </i> <b> 3 </b> Pineapple </p>

它可以呈现类似的东西

1苹果2橙色3菠萝

如何获取的关系

{"1": "Apple", "2": "<i> Orange </i>, "3": "Pineapple"}

我尝试过使用beautifulsoup标签.next,但它没有返回标签,而是停止

我试过使用beautiuloup tag.find(text = True, recursive = False)除了n 外什么都不返回

我试过tags.findAll("b")

for i in b:
    print i.text
    print tags.find(i).text

我在标签中查找了解析标签,但没有找到真正适合一些建议正则表达式的东西(听起来很麻烦),还有一些说它不能完成(没有真正的帮助)

我想我要找到的是如何在两个标签之间获取html。我试着遍历.nextSibling比特,它最终给了我一个unicode空间,所以不能继续遍历。

有人有这方面的经验吗?

<p>:中的每个<b>标记前后累积元素(标记和文本)

#!/usr/bin/env python
from collections import defaultdict
from BeautifulSoup import BeautifulSoup
d = defaultdict(list) # data structure to hold the result
soup = BeautifulSoup(html)
i = 0
for el in soup.p.contents:
    if getattr(el, 'name', None) == 'b':
       i += 1  # switch to next <b> element
    else:
       d[i].append(el)
import pprint
pprint.pprint(dict(d))

它正确地表达了意图,但它并不像可能的那样可读和高效

输出

{0: [u' '],
 1: [u' Apple '],
 2: [u' ', <i> Orange </i>, u' '],
 3: [u' Pineapple ']}

最新更新