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

相关推荐
纪念 22933 分钟前
C++ 算法基础 (差分)
开发语言·c++·算法
databook3 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈3 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao4 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
码农小河665 小时前
基于PHP的电商后台蜜罐系统
开发语言·php
starzy19905 小时前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala
ShineWinsu6 小时前
对于Qt:QTreeWidget常见属性以及QTreeWidgetItem类的解析
开发语言·c++·qt·gui·客户端·多叉树·qtreewidget
落羽的落羽6 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
用户019027581616 小时前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
wuyk5556 小时前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite