【问题标题】:Extract content from span tag in python从python中的span标签中提取内容
【发布时间】:2020-10-06 04:09:42
【问题描述】:

我正在尝试从https://www.lamudi.com.mx/nuevo-leon/departamento/for-rent/?page=1 中提取真实状态帖子的数据

我正在尝试使用以下内容抓取卧室、浴室和平方米的内容:

tags2 = soup('span',{'class':'KeyInformation-label_v2'})
for tag in tags2:
    tagl = tag.get_text().strip()
    print(tagl)

但我现在需要实际数据。这是 HTML 的外观(卧室 = recámara,浴室 = baño,平方米 = contruidos): </span>, <span class="icon-pin"></span>, <span>Grañ Francisco Villa ote San Pedro, San Pedro Garza García</span>, <span class="PriceSection-FirstPrice">$ 7,500</span>, <span class="PriceLabel"></span>, <span class="KeyInformation-value_v2">1</span>, <span class="KeyInformation-label_v2">Recámara</span>, <span class="KeyInformation-value_v2">1</span>, <span class="KeyInformation-label_v2">Baño</span>, <span class="KeyInformation-value_v2">50 m²</span>, <span class="KeyInformation-label_v2">Construidos </span>, <span class="KeyInformation-value_v2">

【问题讨论】:

  • 你的代码返回了什么? tag1.text 应该可以工作

标签: python web-scraping beautifulsoup


【解决方案1】:

对于标签内的文本,您需要使用 tag.string 方法

来自美汤documentation

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>', 'html.parser')
tag = soup.b
tag.string
# 'Extremely bold'

【讨论】:

    【解决方案2】:

    'KeyInformation-label_v2' 类只返回属性的名称。您需要类 'KeyInformation-value_v2' 来获取值。

    您也可以为每个列表添加标题。请注意,有一些重复。

    titles = soup('div', {'class':'KeyInformation-attribute_v2'})
    labels = soup('span', {'class':'KeyInformation-label_v2'})
    values = soup('span', {'class':'KeyInformation-value_v2'})
    
    for title, (label, value) in zip(titles, zip(labels, values)):
        print(title.find('a')['title'], label.string, value.string.strip())
    

    输出:

    Loft en Renta Amueblado Una Recámara Cerca Udem  Recámara 1
    Loft en Renta Amueblado Una Recámara Cerca Udem  Baño 1
    Loft en Renta Amueblado Una Recámara Cerca Udem  Construidos  50 m²
    Loft en Renta Amueblado Una Recámara Cerca Udem  Recámara 1
    Loft en Renta Amueblado Una Recámara Cerca Udem  Baño 1
    Loft en Renta Amueblado Una Recámara Cerca Udem  Construidos  50 m²
    DEPARTAMENTO EN RENTA SAN JERONIMO EQUIPADO Recámaras 3
    DEPARTAMENTO EN RENTA SAN JERONIMO EQUIPADO Baños 2
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2018-11-10
      • 2017-03-13
      • 2020-04-17
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多