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

相关推荐
卿卿的产品经理日记几秒前
【AI产品经理实战】Day 37|拆开 JSON 与 EXE:数据都有格式
人工智能·笔记·python·json·产品经理
wdfk_prog17 分钟前
LWIP教程 15:IPv4 与 IPv6——从网络层工作原理到嵌入式工程取舍
运维·开发语言·网络·笔记·学习·智能路由器·ip
棉猴22 分钟前
玩游戏学Python10-算术运算符应用2
开发语言·python·玩游戏·游戏编程
tachibana227 分钟前
Go 语言的 Map 是否是并发安全的?
开发语言·数据结构·后端·golang·go·语言
后除30 分钟前
Go 实战: 使用 Wails v2.15 构建轻量级的桌面应用 - 仿微信登录界面
开发语言·微信·golang
坤坤子吖30 分钟前
Linux 进程信号入门——从 Ctrl+C 到 kill
linux·开发语言·c++·笔记·学习
deepseek2332 分钟前
Dependabot匿名私有仓库开放后仍更新失败?组织级镜像的访问边界与排查实战
python·github·devops·软件供应链·dependabot
看浪的路人37 分钟前
第8讲:RAG 生产化——Go 实现亿级向量召回 + 混合检索 + 重排序 Pipeline
开发语言·后端·golang
曲径海盗38 分钟前
【Python 学习第 28 天】字符串基础
python·学习笔记·编程入门
tachibana238 分钟前
Go 语言 Map 的扩容过程是怎样的?
开发语言·后端·golang·go·语言