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

相关推荐
一定要AK2 分钟前
Java流程控制
java·开发语言·笔记
河西石头2 分钟前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置
不懒不懒15 分钟前
【卷积神经网络作业实现人脸的关键点定位功能】
开发语言·python
321.。15 分钟前
Linux 进程控制深度解析:从创建到替换的完整指南
linux·开发语言·c++·学习
酉鬼女又兒19 分钟前
零基础快速入门前端Web存储(sessionStorage & localStorage)知识点详解与蓝桥杯考点应用(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯·html
Bert.Cai20 分钟前
Python集合简介
开发语言·python
tryCbest24 分钟前
Java和Python开发项目部署简介
java·开发语言·python
ZTLJQ25 分钟前
任务调度的艺术:Python分布式任务系统完全解析
开发语言·分布式·python
阿里嘎多学长26 分钟前
2026-03-31 GitHub 热点项目精选
开发语言·程序员·github·代码托管
敏编程31 分钟前
一天一个Python库:isodate - 处理 ISO 8601 日期时间格式
python