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

相关推荐
扛麻袋的少年41 分钟前
7.Kotlin的日期类
开发语言·微信·kotlin
麻辣清汤1 小时前
结合BI多维度异常分析(日期-> 商家/渠道->日期(商家/渠道))
数据库·python·sql·finebi
钢铁男儿1 小时前
Python 正则表达式(正则表达式和Python 语言)
python·mysql·正则表达式
钢铁男儿1 小时前
Python 正则表达式实战:解析系统登录与进程信息
开发语言·python·正则表达式
野生技术架构师2 小时前
2025年中高级后端开发Java岗八股文最新开源
java·开发语言
前端小趴菜052 小时前
python - range
python
☺����2 小时前
实现自己的AI视频监控系统-第一章-视频拉流与解码1
人工智能·python·音视频
静若繁花_jingjing2 小时前
JVM常量池
java·开发语言·jvm
前端小趴菜052 小时前
python - 元组常用操作
python
前端小趴菜052 小时前
python - 列表方法
python