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

相关推荐
自由的好好干活25 分钟前
使用Qoder编写ztdaq的C#跨平台示例2
开发语言·c#·ai编程
2501_941111511 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
赵财猫._.2 小时前
Native API开发:C++与ArkTS混合编程实战
开发语言·c++·harmonyos
普通网友3 小时前
基于C++的操作系统开发
开发语言·c++·算法
bitbrowser3 小时前
哪些指纹浏览器支持模拟SSL指纹
网络·python·网络协议·ssl
狂团商城小师妹3 小时前
JAVA外卖霸王餐CPS优惠CPS平台自主发布小程序+公众号霸王餐源码
java·开发语言·小程序
ycydynq3 小时前
自动化爬虫selenium
爬虫·selenium·自动化
2501_941111344 小时前
C++中的策略模式高级应用
开发语言·c++·算法
limenga1024 小时前
TensorFlow Keras:快速搭建神经网络模型
人工智能·python·深度学习·神经网络·机器学习·tensorflow
心软小念4 小时前
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍
java·开发语言·python