Python小试牛刀:第一次爬虫,获取国家编码名称

使用场景:

需要初始化国家(地区表),字段有国家名称、国家编码等等。

解决方案:

使用requests发送请求,使用bs4解析得到的HTML,打开F12,查看元素,(可以Ctrl+S直接保存HTML使用VS code 打开更加清晰)找到数据所在标签,再根据标签获取内容。获取需要的数据,再存储到数组,最后使用pandas将数据转成DataFrame,调用to_excel方法导出。

python 复制代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

# 目标网页URL
url = 'https://www.guojiadaima.com/'

# 发送HTTP请求获取网页内容
response = requests.get(url)
response.encoding = 'utf-8'  # 根据网页的编码调整

# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(response.text, 'html.parser')

# 找到数据所在的标签
tbodyData = soup.find('tbody')

# 初始化数据列表
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()  # 中文简称
            english_name = columns[4].text.strip()  # 英文简称
            iso2_code = columns[5].text.strip()  # ISO 2
            iso3_code = columns[6].text.strip()  # ISO 3
            numerical_code = columns[7].text.strip()  # 数字代码
            ip_code = columns[9].text.strip()  # 数字代码

            data.append({
                '国家名称': country_name,
                '英文名称': english_name,
                '国家编码2': iso2_code,
                '国家编码3': iso3_code,
                '数字代码': numerical_code,
                '域名后缀': ip_code
            })

# 打印提取的数据
for item in data:
    print(item)

# 将数据转换为DataFrame
df = pd.DataFrame(data)
print(df)

# 导出到Excel文件
# index=False表示不导出DataFrame的索引
df.to_excel('countries_codes.xlsx', index=False)

# 指定输出的Excel文件的完整路径
# 假设你想要将文件保存在C盘的某个文件夹中
output_path = 'C:/Users/YourUsername/Documents/output.xlsx'
# 或者在Linux/macOS系统中使用正斜杠(/)或双反斜杠(\\)作为路径分隔符
# output_path = '/home/yourusername/Documents/output.xlsx'
# 或者
# output_path = 'C:\\Users\\YourUsername\\Documents\\output.xlsx'
df.to_excel(output_path, index=False)

需要使用的依赖:

相关推荐
try2find11 分钟前
agent环境安装spacy
python·智能体
ellenwan202615 分钟前
期货程序化开平标志错了总拒单:天勤 last_msg 排查思路
python
绵绵细雨中的乡音18 分钟前
监控显示一切正常,可用户根本打不开网站——Blackbox Exporter帮我找到了真相(1)
开发语言·php
c++之路19 分钟前
CMake 系列教程(五):进阶技巧
c语言·开发语言·c++
踏着七彩祥云的小丑20 分钟前
Go学习第5天:变量作用域 + 数组 + 指针
开发语言·学习·golang·go
装不满的克莱因瓶20 分钟前
自动微分的原理:计算图与前向传播
人工智能·pytorch·python·数学·ai·微积分·计算图
Sam_Deep_Thinking25 分钟前
java中的class到底是个什么东西?
java·开发语言·面试
console.log('npc')1 小时前
将 Figma 接入 Codex MCP:从 `/plugins` 到本地插件配置的完整教程
前端·人工智能·python·figma·code·codex·mcp
资深流水灯工程师1 小时前
PySide6 QMainWindow与QWidget秒解
开发语言·python
popcorn_min1 小时前
California Housing 可复现回归实验:随机森林预测加州房价
python