gpt4 book ai didi

python - Beautifulsoup 正在从表中提取四舍五入的小数(可见的)而不是实际的单元格值

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:35 24 4
gpt4 key购买 nike

尝试从网页表格中提取数据。页面上显示的数据是四舍五入的小数点后 3 位,但实际单元格值是小数点后 4 位。我需要完整的、未四舍五入的数字。

我的循环:

for i in range(0,20):
soup = BeautifulSoup(html_source,'lxml')
table = soup.find_all('table')[i]
df = pd.read_html(str(table))
print(region,i)
print( tabulate(df[0], headers='keys', tablefmt='psql') )

网页元素:

 <span class="price-data " data-amount="{&quot;regional&quot;: 
{&quot;asia-pacific-east&quot;:0.022,&quot;japan-
east&quot;:0.0176,&quot;japan-west&quot;:0.0206,&quot;us-
west&quot;:0.0164,&quot;us-west-2&quot;:0.0144,&quot;us-west-
central&quot;:0.018,&quot;west-india&quot;:0.0193}}" data-decimals="3"
data-decimals-force="3" data-month-format="{0}/month" data-hour-format="
{0}/hour" data-region-unavailable="N/A" data-has-valid-
price="true">$0.018/hour</span>

我的代码显示 0.018/hour,我需要它显示 0.0176/hour

注意:这是针对 japan-east 的(示例数据也有 japan-west)。

最佳答案

假设 JSON 格式正确,您可以从 data-amount 中提取它<span> 中的属性如下:

from bs4 import BeautifulSoup
import html
import json

html_text = """<span class="price-data " data-amount="{&quot;regional&quot;:{&quot;asia-pacific-east&quot;:0.022,&quot;japan-east&quot;:0.0176,&quot;japan-west&quot;:0.0206,&quot;us-west&quot;:0.0164,&quot;us-west-2&quot;:0.0144,&quot;us-west-central&quot;:0.018,&quot;west-india&quot;:0.0193}}" data-decimals="3" data-decimals-force="3" data-month-format="{0}/month" data-hour-format="{0}/hour"data-region-unavailable="N/A" data-has-valid-price="true">$0.018/hour</span>"""

soup = BeautifulSoup(html_text, "html.parser")
da = html.unescape(soup.span['data-amount'])
data_amount = json.loads(da)

print(data_amount['regional']['japan-east'])

将显示:

0.0176

关于python - Beautifulsoup 正在从表中提取四舍五入的小数(可见的)而不是实际的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54594878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com