Python网页抓取获取欧元价格后如何转换为int整数?
解决方法
首先先修正你原有代码的两处笔误,否则会直接抛出运行异常:
bs4.BeatifulSoup拼写错误,正确写法为bs4.BeautifulSoup- 解析器参数
html.parster拼写错误,正确写法为html.parser
金额提取转换逻辑
- 提取span标签内的文本内容,去除首尾多余的空白字符
- 移除金额前的€符号,将剩余的数字字符串转换为float类型
- 按业务需求转换为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
相关产品推荐
相关产品推荐

