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

相关推荐
baopixiaoz8 分钟前
BeeQuant × BeeAgent:AI驱动智能交易
大数据·人工智能·python·区块链
名字还没想好☜13 分钟前
Go 标准库 flag 包实战:参数解析、子命令、自定义 Value 类型与默认值
开发语言·后端·golang·go
公爵爱学习18 分钟前
无人机定点飞行-介绍
开发语言·图像处理·python·学习·线性回归·无人机
stillstream_ink19 分钟前
OpenCart UI 自动化测试实战:POM 四层架构 + 失败自动截图 + 飞书通知
python·测试
databook22 分钟前
Beta 分布:如何用“成功”和“失败”来预测下次尝试
python·数据挖掘·数据分析
西西弗Sisyphus23 分钟前
Qt 分类导航区的实现
开发语言·qt
zhanghaha131431 分钟前
Python进阶教程:27_subprocess 模块 零基础超详细教程
开发语言·python
兄弟加油,别颓废了。32 分钟前
bugku题目
开发语言·前端·python
新网企兴32 分钟前
2026西安GEO推广选哪家?新网企兴帮您精准获客
人工智能·python
zh_xuan36 分钟前
c++ string_view
开发语言·c++