python - 如何从嵌入了 div 的 beautifulsoup4 的 div 中获取第一个字符串
问题描述
我正在尝试从网站中提取价格。
我编写的代码可以做到这一点,但是当网站的价格也显示旧价格时,它会返回“none”而不是价格字符串。
这是没有旧价格的代码示例(我的代码作为字符串返回)
<div class="xl-price rangePrice">
535.000 €
</div>
这是带有旧价格的代码示例(我的代码返回为“无”)
< 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'
当我只想要数字时。
将不胜感激!
解决方案
这是您问题的示例代码。
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)
推荐阅读
- angular7 - 我想在 for 循环中显示特定记录的标签文本
- laravel - 如何从 laravel 中的 8/29/2011 1:00 PM 之类的字符串中拆分日期和时间
- .net - 如何手动设置为未经授权并重定向到自定义页面?
- php - nginx 不使用 VSCode 远程容器扩展(docker compose)打开 localhost
- flutter - 从另一个屏幕移回屏幕后颤动调用一个函数
- jquery - 我想通过jquery获取按钮旁边输入框的值
- python - 旧版 chrome(v48),是否有适合旧版 chrome 的 chromedriver?
- python - 需要在烧瓶 restplus 中发送响应后 2 小时后执行方法
- javascript - 使用 react redux 和 firebase 按值过滤表
- json - 在 NIFI 中将 Json 拆分为多个 json