【问题标题】:Python BeautifulSoup - Text Between DivPython BeautifulSoup - div之间的文本
【发布时间】:2019-03-11 19:47:43
【问题描述】:

我正在处理一个网络爬虫项目,但无法让 BeautifulSoup 给我 Div 之间的文本。下面是我的代码。关于如何让 python 只打印没有“Div to /Div”且没有空格的“5x5”的任何建议?

source = requests.get('https://www.stor-it.com/self-storage/meridian-id-83646').text
soup = BeautifulSoup(source, 'lxml')
unit = soup.find('div', class_="unit-size")
print (unit)

此脚本返回以下内容:

<div class="unit-size">
                                    5x5                                 </div>

【问题讨论】:

  • 只做unit.text.strip()

标签: python beautifulsoup


【解决方案1】:

您可以使用文本检索文本,然后剥离以删除空格 试试unit.text.strip()

【讨论】:

    【解决方案2】:

    将您的打印声明从 print(unit) 更改为 print(unit.text)

    【讨论】:

      【解决方案3】:

      使用更快的 css 类选择器

      from bs4 import BeautifulSoup
      source= '''
      <div class="unit-size">
                                          5x5                                 </div>
      '''
      soup = BeautifulSoup(source, 'lxml')
      unit = soup.select('.unit-size')
      print(unit[0].text.strip())
      

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 2013-05-25
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多