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

相关推荐
m0_61360701几秒前
小土堆-P3-笔记
pytorch·python·深度学习
rgeshfgreh1 分钟前
Python高效开发:标准库与第三方库实战指南
python
十五年专注C++开发3 分钟前
VS2019编译的C++程序,在win10正常运行,在win7上Debug正常运行,Release运行报错0xC0000005,进不了main函数
开发语言·c++·报错c0x0000005
一条咸鱼_SaltyFish3 分钟前
[Day13] 微服务架构下的共享基础库设计:contract-common 模块实践
开发语言·人工智能·微服务·云原生·架构·ai编程
隐退山林5 分钟前
JavaEE:多线程初阶(一)
java·开发语言·jvm
虎冯河7 分钟前
阿里云 + 宝塔面板环境Python 项目从 0 到 1 部署全流
python·阿里云·云计算
C_心欲无痕9 分钟前
ts - 模板字面量类型与 `keyof` 的魔法组合:`keyof T & `on${string}`使用
linux·运维·开发语言·前端·ubuntu·typescript
最贪吃的虎11 分钟前
Redis其实并不是线程安全的
java·开发语言·数据库·redis·后端·缓存·lua
鹿衔`12 分钟前
PySpark 大规模造数任务优化与实施总结文档
python·pyspark
深蓝海拓12 分钟前
PySide6从0开始学习的笔记(二十三)使用QRunnable在线程池中执行临时任务
笔记·python·qt·学习·pyqt