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

相关推荐
2401_879693871 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
@PHARAOH1 小时前
HOW - Go 开发入门(一)
开发语言·后端·golang
xixihaha13247 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
xixihaha13247 小时前
Python游戏中的碰撞检测实现
jvm·数据库·python
myloveasuka8 小时前
Java与C++多态访问成员变量/方法 对比
java·开发语言·c++
2301_821700538 小时前
C++编译期多态实现
开发语言·c++·算法
奥地利落榜美术生灬8 小时前
c++ 锁相关(mutex 等)
开发语言·c++
xixihaha13248 小时前
C++与FPGA协同设计
开发语言·c++·算法
重庆小透明8 小时前
【java基础篇】详解BigDecimal
java·开发语言
ID_180079054738 小时前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json