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

如何在Python中将终端输出导出至CSV文件?附代码求助

解决方法

首先你需要先批量收集提取到的餐厅名称,再利用pandas将数据导出为CSV文件。修改后的完整代码如下:

import pandas as pd
from bs4 import BeautifulSoup as bs
import requests

url = "https://www.yelp.com/search?find_desc=North+Indian+Thali&find_loc=Portland%2C+OR"

response = requests.get(url)
soup = bs(response.content,'html.parser')

content = soup.find_all('h3',attrs={'class':'css-1agk4wl'})

# 创建空列表存储所有餐厅名称
restaurant_names = []

for links in content:
    # 增加异常处理,避免页面元素缺失导致代码报错
    try:
        name = links.find('a','css-19v1rkv').get('name')
        restaurant_names.append(name)
    except AttributeError:
        # 跳过不符合结构的元素
        continue

# 将列表转换为DataFrame格式
df = pd.DataFrame({'Restaurant Name': restaurant_names})

# 导出到CSV文件,index=False去除自动生成的索引列
df.to_csv('yelp_indian_thali_restaurants.csv', index=False, encoding='utf-8')

print("数据已成功导出到yelp_indian_thali_restaurants.csv")

关键修改说明:

  • 新增restaurant_names列表,用于批量存储所有提取到的餐厅名称
  • 添加try-except异常处理,适配页面可能存在的非目标元素,避免代码中途崩溃
  • 通过pd.DataFrame将列表转换为标准表格结构
  • 调用to_csv方法完成导出,设置index=False避免写入冗余索引,指定编码防止中文乱码

内容的提问来源于stack exchange,提问作者Shubham Vashisht

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:17:02