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

相关推荐
qq_2837200520 分钟前
Python Celery + FastAPI + Vue 全栈异步任务实战
vue.js·python·fastapi
2401_8858850433 分钟前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
zs宝来了36 分钟前
AQS详解
java·开发语言·jvm
telllong1 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
wjs20243 小时前
JavaScript 条件语句
开发语言
lulu12165440783 小时前
Claude Code Harness架构技术深度解析:生产级AI Agent工程化实践
java·人工智能·python·ai编程
阿里加多3 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
2301_792674864 小时前
java学习day29(juc)
java·开发语言·学习
周末也要写八哥4 小时前
MATLAB R2025a超详细下载与安装教程(附安装包)
开发语言·matlab
blog_wanghao5 小时前
基于Qt的串口调试助手
开发语言·qt