You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用BeautifulSoup去除CSV双引号并统一数字格式

解决BeautifulSoup抓取新冠数据的CSV格式与数字格式化问题

问题1:CSV值被双引号分隔

csv模块的writer默认会对包含特殊字符(比如原数字里的逗号)的字段添加双引号。解决思路一是先清除数字中的逗号(解决问题2的同时减少引号触发场景),二是通过设置writer的quoting参数控制引号行为,比如用csv.QUOTE_MINIMAL(仅必要时加引号)或csv.QUOTE_NONE(完全不加引号,需确保字段无逗号等分隔符)。

问题2:数字千位分隔逗号处理

编写辅助函数统一处理所有数字字段,去除逗号和空白字符,转换为纯数字格式,同时兼容空值场景。

修改后的完整代码

import requests
from bs4 import BeautifulSoup
import csv

def clean_number(num_str):
    # 去除空白字符和逗号,空值返回空字符串
    cleaned = num_str.strip().replace(',', '')
    return cleaned if cleaned else ''

response = requests.get('https://www.worldometers.info/coronavirus/#news').content
soup = BeautifulSoup(response, 'lxml')
tbody = soup.find('table', id='main_table_countries_today').find('tbody').find_all('tr')[8:11]

with open('corona1.csv', 'w', newline='', encoding='utf-8') as csv_file:
    # 设置引号规则,避免不必要的双引号;newline=''防止空行,utf-8避免乱码
    csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['countries','total_cases','total_deaths','total_recovered','active_cases','total_cases_in_1m','deaths_in_1m','population'])

    for value in tbody:
        countries = value.find_all('td')[1].text.strip()
        total_cases = clean_number(value.find_all('td')[2].text)
        total_deaths = clean_number(value.find_all('td')[4].text)
        total_recovered = clean_number(value.find_all('td')[6].text)
        active_cases = clean_number(value.find_all('td')[8].text)
        total_cases_in_1m = clean_number(value.find_all('td')[10].text)
        deaths_in_1m = clean_number(value.find_all('td')[11].text)
        population = clean_number(value.find_all('td')[14].text)

        csv_writer.writerow([countries, total_cases, total_deaths, total_recovered, active_cases, total_cases_in_1m, deaths_in_1m, population])

关键修改说明

  • clean_number函数:统一处理所有数字字段,去除逗号和多余空白,保证输出为纯数字字符串。
  • csv.writer参数优化:quoting=csv.QUOTE_MINIMAL减少不必要的双引号;newline=''解决Windows环境下CSV空行问题;encoding='utf-8'避免国家名称等字符乱码。
  • 国家名称增加strip()处理,清除可能的首尾空白字符。

内容的提问来源于stack exchange,提问作者Ömer Sevban Tümer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:02:25