【问题标题】:Can't get text immediately after </span> tag using BeautifulSoup使用 BeautifulSoup 无法在 </span> 标记后立即获取文本
【发布时间】:2020-07-04 13:54:02
【问题描述】:

目前,在我的代码中,我分解了一个更大的汤以使用此代码获取所有“td”标签:

floorplans_all = sub_soup.findAll('td', {"data-label":"Rent"})
floorplan_soup = soup(floorplans_all[0].prettify(), "html.parser")
rent_span = floorplan_soup.findAll('span', {"class":"sr-only"})

print(floorplans_all)

最终得到以下结果:

<td data-label="Rent" data-selenium-id="Rent_6">
    <span class="sr-only">
      Monthly Rent
     </span>
     $2,335 -
     <span class="sr-only">
      to
     </span>
     $5,269
    </td>

打印rent_span看起来像这样:

  [<span class="sr-only">
  Monthly Rent
 </span>, <span class="sr-only">
  to
 </span>]

我似乎无法从上面得到“$2,335 -”和“$5,269”。我一直在尝试遍历 HTML 树,但无法获取标签之间的文本。

【问题讨论】:

  • 可以添加你的python代码
  • 请附上您尝试过的代码

标签: python html beautifulsoup


【解决方案1】:

td 元素有五个子元素:

  • 仅包含空格的文本节点
  • 包含“月租”的span 节点
  • 包含“$2,335 -”的文本节点
  • 一个包含“to”的span节点
  • 包含“$5,269”的文本节点

您可以使用children 属性来迭代这些孩子:

soup = BeautifulSoup(text, 'html.parser')

for child in soup.td.children:
    print(repr(child))
'\n'
<span class="sr-only">
      Monthly Rent
     </span>
'\n     $2,335 -\n     '
<span class="sr-only">
      to
     </span>
'\n     $5,269\n    '

如果要显式查找文本节点,可以搜索 span 节点并每次获取下一个兄弟节点:

>>> [span.next_sibling.string.strip() for span in soup.td.find_all(class_='sr-only')]
['$2,335 -', '$5,269']

【讨论】:

    【解决方案2】:
    soup = BeautifulSoup(res, 'html.parser')
    
    row = soup.find('td', {'data-label': "Rent"})
    for all in row.find_all('span'):
        print(all.text.strip())
    

    输出将如下所示

    Monthly Rent
    $2,335
     $5,269
    

    【讨论】:

    • 您的代码只会输出“月租”和“to”,因为货币值不是在 span 标签内。
    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多