将Beautiful Soup的 .text转换为浮点数
我正在尝试从来自HTML网站的文本中创建一个浮点数列表,因为我想检查该列表中的价格是否在我的预算内或更低。我正在使用 find_all()(来自Beautiful Soup 4)来在不带标签的情况下获取文本:
import requests
from bs4 import BeautifulSoup
for price1 in tag:
print("Best price", price1.text)
print("-----")
tag = doc.find_all("div", class_ = "_text_j98bt_1 _text__size_m_j98bt_40 _text__weight_bold_j98bt_83 _text__style_normal_j98bt_95 _text__decoration_normal_j98bt_104 _content-price_1gow4_85")
for price2 in tag:
print(price2.text)
结果:
Best price 1.36
-----
1.35 $
1.7 $
3.25 $
有两个独立的价格变量,因为网站根据位置使用两种不同的价格标签,其中class标签包含大多数价格,数量也在不断变化。然而,如果我尝试从 for price2 in tag: 函数分开打印 price2.text,它只打印最后一个 price2。
解决方案
在 for-循环之后,变量 price2 只有最后一个值,这是正常的。
变量始终只有一个值,但在每次循环中这个值都不同。
这就是 for-循环的工作原理。
要获得所有值,你需要为它创建一个新的列表,并将 append() 的值加入其中。
# - before loop -
all_values = []
# - loop -
for price2 in tag:
print(price2.text)
all_values.append(price2.text)
# - after loop -
print(all_values)
# or
for value in all_values:
print(value)
最终把所有代码写成一行,作为列表推导式
all_values = [price2.text for price2 in tag]
如果你想把它作为浮点数值,则需要使用 float(text),但首先必须移除 $。你可以把它替换为空字符串。
value = float(price2.text.replace("$", ""))
all_values.append(value)
或者按空格分割,获取第一个元素
value = float(price2.text.split(" ")[0])
all_values.append(value)
最终把所有代码写成一行的列表推导式
all_values = [float(price2.text.replace("$", "") for price2 in tag]
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。