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

相关推荐
一只月月鸟呀4 分钟前
移动端tap与click的区别 && 点透事件
开发语言·前端·javascript
雨落在了我的手上5 分钟前
Java数据结构(六):链表的介绍
java·开发语言·数据结构
影寂ldy8 分钟前
C# HttpClient 分片下载、断点续传、暂停取消(完整项目知识点)
开发语言·c#
独隅13 分钟前
DevEco Code Plan+Build 双 Agent 协同开发效率实测
java·开发语言
DogDaoDao18 分钟前
【GitHub】WorldMonitor:一个工程极致主义的实时全球情报仪表盘深度解析
python·程序员·架构·github·go语言·worldmonitor·实时全球情报
艾斯特_1 小时前
混合检索与重排:提升召回与排序质量
后端·python·ai
网安墨雨1 小时前
MySQL数据库 SQL语句详解
自动化测试·软件测试·数据库·python·sql·mysql
柠檬味的Cat1 小时前
GEO优化系统哪家技术强
人工智能·python
KaMeidebaby1 小时前
卡梅德生物技术快报|抗体筛选:抗体筛选中的噬菌体展示四参数调优——从流程设计到数据验证
开发语言·前端·javascript
大黄说说1 小时前
接口频繁超时、报错?后端常见排查思路总结
开发语言·php