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打开,可以更清晰分析数据所在的标签。

相关推荐
北冥you鱼2 分钟前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
这不小天嘛6 小时前
JAVA八股——J集合篇
java·开发语言
hboot7 小时前
AI工程师第五课 - 大语言模型基础
python·llm·fastapi
AOwhisky7 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
STLearner8 小时前
ICML 2026 | LLM×Graph论文总结[1]【图基础模型,文本属性图,多模态属性图,图对齐,图提示学习,关系深度学习
论文阅读·人工智能·python·深度学习·学习·机器学习·数据挖掘
习明然9 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
喜欢的名字被抢了10 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
夏季疯11 小时前
读论文:STARS 是什么结构?一个统一的歌声自动标注框架
python
从零开始的代码生活_12 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
wabs66612 小时前
关于单调栈【力扣739.每日温度的思考】
java·开发语言