Python爬虫:获取国家货币编码、货币名称

使用场景:

需要获取货币编码,并初始化到数据库。

解决方案:

python 复制代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

# 目标网页URL
url = 'http://www.cnhuilv.com/currency/'

# 发送HTTP请求获取网页内容
response = requests.get(url)
# 根据网页的编码调整
response.encoding = 'utf-8'
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取div标签数据,需要指定class名称
tbodyData = soup.find('div', class_='table-responsive rb1')
# 初始化数据列表
data = []
# 提取表格中的数据
for row in tbodyData.find_all('tr')[1:]:  # 跳过表头
    columns = row.find_all('td')
    if len(columns) > 1:
        if columns[3].text.strip() != '':
            country_name = columns[3].text.strip()
            numerical_code = columns[1].text.strip()
            currency_code = columns[0].text.strip()
            currency_name = columns[2].text.strip()

            data.append({
                '国家名称': country_name,
                '数字代码': numerical_code,
                '货币代码': currency_code,
                '货币名称': currency_name
            })
# 打印提取的数据
for item in data:
    print(item)

# 将数据转换为DataFrame
df = pd.DataFrame(data)
# 导出到Excel文件
output_path = 'C:\\Users\\Administrator\\Desktop\\货币1.xlsx'
df.to_excel(output_path, index=False)

技巧:将html文件保存到本地,使用VScode打开,可以更清晰分析数据所在的标签。

相关推荐
2601_956319883 小时前
2026年下半年,量化学习要把交易认知和技术实现接起来
人工智能·python
Hhy_11074 小时前
《C++深度解构02》类和对象(上)——定义规范、内存对齐与 this 指针全解
c语言·开发语言·c++·学习·visual studio
EW Frontier4 小时前
【雷达信号处理】5 个阵元追平 16 个阵元:稀疏阵列 STAP 的实测报告【附python+matlab代码】
python·matlab·信号处理·雷达·mimo·稀疏阵列·stap
电子云与长程纠缠4 小时前
UE5 Lyra PocketWorld进行3D内容UI预览 - 下
开发语言·学习·游戏·ui·ue5
卷无止境4 小时前
FastAPI的测试事件在测什么?
后端·python·fastapi
selfsongs4 小时前
Python学习之——multiprocessing 多进程编程
python
平常心的技术小牛4 小时前
Qt-快速上手-QLabel
开发语言·qt
卷无止境4 小时前
FastAPI CLI 你需要认识这把命令行利器
后端·python·fastapi
XR1234567884 小时前
工厂办公楼无线网络:多楼层覆盖与访客体验怎么选?
开发语言·php
拿本唠嗑AI研究4 小时前
现代前端架构爬虫指南:从静态页面到 React/Vue 单页应用
前端·爬虫·架构