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

标签 python selenium web-scraping beautifulsoup

尝试从网页表格中提取数据。页面上显示的数据是四舍五入的小数点后 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/

相关文章:

python - 将应用程序中的联系表单插入 Django 中的类 View

python - Paypal与谷歌应用引擎-python集成

javascript - 如何使元素在 selenium webdriver 中可见?

python - 使用 Python 3.4 在 Textmate 2 中输出错误

python - 获取列表和元组列表的交集

javascript - 如何点击包含变量为 "href"属性的链接?

selenium - 网络驱动程序错误: disconnected: unable to connect to renderer

python-3.x - 使用 CSV 查询网站时出现问题,输入不正确

python - 来自结果集对象的 beautifulsoup 标题

java - 通过直接更改 FormData keyVals 的列表 jsoup 来更改 FormElement 的信息