【问题标题】:Using beautifulsoup to parse tag with some text使用 beautifulsoup 解析带有一些文本的标签
【发布时间】:2012-10-27 19:00:53
【问题描述】:

一些html代码包含一些dt标签,如下所示:

<dt>PLZ:</dt>
<dd>
8047
</dd>

我想在dt 标记后面的dd 标记中找到带有文本PLZ: 的文本。根据文档,我正在尝试以下操作:

number = BeautifulSoup(text).find("dt",text="PLZ:").findNextSiblings("dd")

使用text 上面的字符串,但我得到的只是一个空列表,而不是我正在寻找的数字(当然是字符串)。也许我误解了文档?

【问题讨论】:

  • 我敢打赌 PLZ: 不匹配(也许你太严格了?)。要进行调试,请尝试将PLZ: 减少到最小的值——如果它完全匹配任何内容,请添加一些PLZ:,直到你得到你所期望的。
  • PLZ:实际上是匹配的。即BeautifulSoup(text).find("dt",text="PLZ:") 部分返回一个打印为PLZ: 的对象。只有最后一步似乎不起作用。或者至少不能以我尝试的方式工作。

标签: python web-scraping beautifulsoup


【解决方案1】:

那就试试吧:

from BeautifulSoup import BeautifulSoup

text = """
<dt>PLZ:</dt>
<dd>
8047
</dd>"""

number = BeautifulSoup(text).find("dt",text="PLZ:").parent.findNextSiblings("dd")
print BeautifulSoup(''.join(number[0]))

或者如果你用 findNext 找到试试:

number = BeautifulSoup(text).find("dt",text="PLZ:").parent.findNext("dd").contents[0]

【讨论】:

    【解决方案2】:

    这对我有用:

    from BeautifulSoup import BeautifulSoup
    
    text = '''<dt>PLZ:</dt>
    <dd>
    8047
    </dd>'''
    
    
    BeautifulSoup(text).find("dt",text="PLZ:").parent.findNextSiblings('dd')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-06
      • 2013-03-20
      • 2013-09-19
      • 1970-01-01
      • 2017-09-24
      • 2021-03-20
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多