You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python网页抓取获取欧元价格后如何转换为int整数?

解决方法

首先先修正你原有代码的两处笔误,否则会直接抛出运行异常:

  • bs4.BeatifulSoup 拼写错误,正确写法为 bs4.BeautifulSoup
  • 解析器参数 html.parster 拼写错误,正确写法为 html.parser

金额提取转换逻辑

  1. 提取span标签内的文本内容,去除首尾多余的空白字符
  2. 移除金额前的€符号,将剩余的数字字符串转换为float类型
  3. 按业务需求转换为int类型:直接强转int会截断小数部分,需要四舍五入可搭配round()方法使用

完整可运行代码

import bs4, requests
 
link = "https://hookpod.shop/products/hookpod-screw-adapter"
 
response = requests.get(link)
response.raise_for_status()
# 修正原有拼写错误
soup = bs4.BeautifulSoup(response.text, 'html.parser')
span_price = soup.find('span', class_='product__price')

if span_price:
    # 提取文本并清理空白
    price_raw = span_price.text.strip()
    # 移除欧元符号后转浮点
    price_float = float(price_raw.removeprefix('€'))
    # 转int,如需四舍五入改为 price_int = round(price_float)
    price_int = int(price_float)
    print(price_int)
else:
    print("未匹配到价格元素")

低版本Python兼容说明

如果你使用的Python版本低于3.9,不支持removeprefix方法,可以替换为以下任意一种写法:

  • 替换符号:price_raw.replace('€', '').strip()
  • 切片提取:price_raw[1:].strip()(仅适用于价格文本首字符固定为€的场景)

内容的提问来源于stack exchange,提问作者h4rak1ri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:54:03