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

相关推荐
E_ICEBLUE几秒前
Python 办公自动化:如何轻松调整 Word/PDF 页面大小为 Legal 尺寸
python·pdf·word
战斗强几秒前
RTX 5090 Grounded-SAM-2 实时 RTSP 跟踪部署指南
python·conda
Wonderful U1 分钟前
Python+Django实战 | 智能图书管理系统:从传统人工到全自动数字化管理
python·信息可视化·django
Johnstons2 分钟前
如何精确模拟网络丢包进行测试?实测指南
开发语言·网络·php·网络测试·网络损伤·弱网模拟
耶夫斯计3 分钟前
【xy_healthy_assistant:LLM+Mem0 +skills个性化助手开发手记】
人工智能·python·健康医疗
csdn_aspnet3 分钟前
Python 霍尔分区算法(Hoare‘s Partition Algorithm)
开发语言·python·算法
❀͜͡傀儡师5 分钟前
告别脚手架:用 JBang 打通 Java、Kotlin、Python 的脚本化开发
java·python·kotlin·jbang
nashane7 分钟前
HarmonyOS 6学习:应用无响应(AppFreeze)故障排查与性能优化指南
人工智能·pytorch·python
程序喵大人7 分钟前
C++与C语言的核心区别是啥
c语言·开发语言·c++
Rain5098 分钟前
GitLab-Runner + AI 代码审查服务 + 远程大模型 全套部署运维实战
linux·运维·人工智能·python·ci/cd·gitlab·ai编程