从一个同时提到卧室数量的字符串中提取平方米的最佳方法是什么?

2024-04-25 13:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取:

<div class="xl-surface-ch"> 
                            &nbsp;84 m²  &nbsp;&nbsp;&nbsp;2 bed.  
                        </div>

link开始,问题是,我只需要这个字符串中的“84”(它们有时也超过2或3位)

更困难的是,有时不提及平方米,如下所示:

<div class="xl-surface-ch"> 
                             &nbsp;&nbsp;&nbsp;2 bed.  
                        </div>

在这种情况下,我需要返回一个0

我最好的尝试是:

    sqm = []
for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
    item = item.contents[0].strip()[0:4]
    item_clean = re.findall("[0-9]{2,4}", item)
    sqm.append(item_clean)

print(sqm)

但这似乎不起作用,也不会是我所需要的最终结果如上所述。 下面是我的代码得到的结果:

[['84'], ['70'], ['80'], ['32'], ['149'], ['22'], ['75'], ['30'], ['23'], ['104'], [], ['95'], ['129'], ['26'], ['55'], ['26'], ['25'], ['28'], ['33'], ['210'], ['37'], ['69'], ['36'], ['19'], ['119'], ['20'], ['20'], ['129'], ['154'], ['25']]

我真的很想知道你们设计了什么样的解决方案,因为我真的认为没有真正的解决方案,特别是因为有时你的建筑没有平方米。。。也许用if语句?不管怎样,我现在就要试试

提前谢谢


Tags: 字符串divcleanforlink情况解决方案ch
1条回答
网友
1楼 · 发布于 2024-04-25 13:39:48
import requests
from bs4 import BeautifulSoup

r = requests.get(
    'https://www.immoweb.be/en/search/apartment/for-sale/leuven/3000')
soup = BeautifulSoup(r.text, 'html.parser')

for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
    item = item.text.strip()
    if 'm²' in item:
        print(item[0:item.find('m')])
    else:
        item = 0
        print(item)

输出:

84 
70 
80 
32 
149 
22 
75 
30 
23 
104 
0
95 
129 
26 
55 
26 
25 
28 
33 
210 
37 
69 
36 
19 
119 
20 
20 
129 
154 
25 

相关问题 更多 >