获取中国银行汇率
原创2025年7月2日大约 1 分钟
获取中国银行汇率
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2025-07-02 14:58
# @Author : Jack
# @File : BocExchangeHelper
"""
BocExchangeHelper
"""
import requests
from bs4 import BeautifulSoup
def get_exchange_rate():
"""
获取中国银行的汇率
:return:
"""
response = requests.get("https://www.bankofchina.com/sourcedb/whpj/index.html", headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
})
response.encoding = "utf-8"
if response.status_code != 200:
print(f"请求失败,状态码: {response.status_code}")
return []
soup = BeautifulSoup(response.text, "html.parser")
table = next((t for t in soup.find_all("table") if len(t.find_all("tr")) > 2), [])
rows = table.find_all("tr")
# 遍历每一行
data = []
for row in rows:
cols = row.find_all("td")
if len(cols) > 0:
currencyCHName = cols[0].get_text(strip=True)
if currencyCHName not in ['港币', '美元']:
continue
foreignBuy = cols[1].get_text(strip=True)
cashBuy = cols[2].get_text(strip=True)
foreignSell = cols[3].get_text(strip=True)
cashSell = cols[4].get_text(strip=True)
referenceRate = cols[5].get_text(strip=True)
publishDate = cols[6].get_text(strip=True)
# 货币名称 现汇买入价 现钞买入价 现汇卖出价 现钞卖出价 中行折算价 发布日期 发布时间
data.append([currencyCHName, foreignBuy, cashBuy, foreignSell, cashSell, referenceRate, publishDate])
return data
if __name__ == '__main__':
for o in get_exchange_rate():
print(o)
显示结果
['港币', '91.13', '91.13', '91.49', '91.49', '91.15', '2025.07.04 16:23:48']
['美元', '715.39', '715.39', '718.4', '718.4', '715.35', '2025.07.04 16:23:48']
根据核心代码做其他扩展功能
- 每隔几分钟存入数据库
- 其他币种汇率获取
- 提供API服务
- 推送手机端