【问题标题】:Finding next occurring tag and its enclosed text with Beautiful Soup使用 Beautiful Soup 查找下一个出现的标签及其包含的文本
【发布时间】:2014-03-16 09:41:16
【问题描述】:

我正在尝试解析标签 <blockquote> 之间的文本。当我输入soup.blockquote.get_text()

我得到了我想要的 HTML 文件中第一个出现的块引用的结果。如何在文件中找到下一个连续的<blockquote> 标签?也许我只是累了,在文档中找不到。

示例 HTML 文件:

<html>
<head>header
</head>
<blockquote>I can get this text
</blockquote>
<p>eiaoiefj</p>
<blockquote>trying to capture this next
</blockquote>
<p></p><strong>do not capture this</strong>
<blockquote>
capture this too but separately after "capture this next"
</blockquote>
</html>

简单的python代码:

from bs4 import BeautifulSoup

html_doc = open("example.html")
soup = BeautifulSoup(html_doc)
print.(soup.blockquote.get_text())
# how to get the next blockquote???

【问题讨论】:

  • 你指的
    是什么,它是 HTML
    == w3schools.com/tags/tryit.asp?filename=tryhtml_blockquote_test。如果是,那么 HTML
    是否需要比其他 HTML TAG 进行任何特殊处理?恕我直言,它并没有留下这个评论来澄清这一点。适用于“其他 HTML 标签”的 bs4 或任何其他类型的 HTML 解析代码应该适用于 HTML -
    ,谢谢。

标签: python html python-2.7 beautifulsoup


【解决方案1】:

使用find_next_sibling(如果不是兄弟,使用find_next

>>> html = '''
... <html>
... <head>header
... </head>
... <blockquote>blah blah
... </blockquote>
... <p>eiaoiefj</p>
... <blockquote>capture this next
... </blockquote>
... <p></p><strong>don'tcapturethis</strong>
... <blockquote>
... capture this too but separately after "capture this next"
... </blockquote>
... </html>
... '''

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> quote1 = soup.blockquote
>>> quote1.text
u'blah blah\n'
>>> quote2 = quote1.find_next_siblings('blockquote')
>>> quote2.text
u'capture this next\n'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2016-06-11
    • 2012-08-09
    相关资源
    最近更新 更多