如何从嵌入了div 4的div中获取第一个字符串

2024-09-30 05:19:26 发布

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

我想从一个网站上提取价格。你知道吗

我写的代码可以做到这一点,但当网站有一个价格,也显示旧的价格,它返回“无”,而不是一个价格字符串。你知道吗

这是一个没有旧价格(我的代码以字符串形式返回)的代码示例

<div class="xl-price rangePrice">
                            535.000 €  
                        </div>

这是一个使用旧价格的代码示例(我的代码返回“none”)

    < div


class ="xl-price rangePrice" >


487.000 €
< span


class ="old-price" > 497.000 € < br > < / span >

< / div >

我试图从中提取代码的页面:pagelink

我的代码:

prices = []
for items in soup.find_all("div", {"class": "xl-price rangePrice"}):
    prices.append(items.string)

print(prices)

我遇到的另一个问题是,它返回如下值:

'\r\n\t\t\t\t\t\t\t\t298.000 € \r\n\t\t\t\t\t\t\t', '\r\n\t\t\t\t\t\t\t\t145.000 € \r\n\t\t\t\t\t\t\t'

当我只想要数字的时候。你知道吗

谢谢你的帮助!你知道吗


Tags: 字符串代码divnone示例网站items价格
3条回答

我现在无法访问计算机,因此请考虑以下准伪代码:

new_price = div_elem.find(text=True, recursive=False)

find_res = div_elem.find('span', attrs={'class': 'old-price'})

if find_res:
    old_price = find_res.get_text(strip=True)

我尽量使事情简单易懂。你知道吗

如果您有任何问题,请告诉我:)

下面是您的问题的示例代码。你知道吗

import re
import requests
page = requests.get("https://www.immoweb.be/en/search/apartment/for-sale/leuven/3000")
print(page.content)

from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')

prices = []
for items in soup.find_all("div", {"class": "xl-price rangePrice"}):
if items.string:
    result = re.findall(r'\d+.\d+', items.string)
    prices.append(result[0])
else:
    soup1 = BeautifulSoup(str(items), 'html.parser')
    for item in soup1.find("div", {"class": "xl-price rangePrice"}):
        if item.string:
            result = re.findall(r'\d+.\d+', item.string)
            if len(result)>0:
                prices.append(result[0])

print(prices)
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-price rangePrice'}):
    item = item.contents[0]
    print(item.strip()[0:-1])

输出:

298.000 
145.000 
275.000 
535.000 
487.000 
159.000 
325.000 
189.000 
139.000 
499.000 
520.000 
249.500 
448.000 
215.000 
225.000 
210.000 
215.000 
218.000 
232.000 
689.000 
228.000 
299.500 
169.000 
135.000 
549.000 
125.000 
160.000 
395.000 
430.000 
210.000 

相关问题 更多 >

    热门问题