【发布时间】:2013-09-02 02:05:09
【问题描述】:
<p>This is the first paragraph with some details</p>
<p><a href = "user123">user1</a><font>This is opening contents for user1</font></p>
<p><font>This is the contents from user1</font></p>
<font><p>This is more content from user1</p></font>
<p><a href = "user234">user2</a><font>This is opening contents for user2</font></p>
<p><font>This is the contents from user2</font></p>
<font><p>This is more content from user1</p></font>
!----There is n number of data like this-----!
这是我的html的结构。我的目标是提取用户及其内容。在这种情况下,它应该打印两个“a”标签之间的所有内容。这只是我的结构的一个例子,但在真正的 html 中,我在两个“a”标签之间有不同类型的标签。我需要一个解决方案来迭代“a”标签下的所有标签,直到找到另一个“a”标签。希望这很清楚。
我试过的代码是:
for i in soup.findAll('a'):
while(i.nextSibling.name!='a'):
print i.nextSibling
我返回一个无限循环。所以如果有人知道我该如何解决这个问题,请与我分享。
预期输出是:
用户名是:user1
text is : 这是为 user1 打开的内容 这是来自 user1 的内容 这是来自 user1 的更多内容
用户名是:user2
text is : 这是为 user2 打开的内容 这是来自 user2 的内容 这是来自 user2 的更多内容
等等……
【问题讨论】:
-
您在第 2 行和第 4 行中缺少结束
</p>。这是您的示例中的错误,还是真的如此? -
你得到一个无限循环的原因是你没有遍历
i的兄弟姐妹,你每次都在看同一个兄弟姐妹。 -
@nickie -- 那是错误的......我现在已经更正了......
-
好的,那么我认为我的解决方案有效。
-
上次编辑后,第 4 行和第 7 行中的标签
<p>和<font>嵌套不正确。
标签: python python-2.7 beautifulsoup