如何将结果导出到Excel或CSV?

2024-06-16 09:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的脚本获取一个品牌的谷歌新闻结果。但是,我希望能够将结果导出到CSV或Excel文件。有人能帮我吗

pip install pygooglenews --upgrade

from pygooglenews import GoogleNews

gn = GoogleNews(country = 'IE')

def get_titles(search):
  stories = []
  search = gn.search(search)
  newsitem = search['entries']
  for item in newsitem:
      story = {
        'title' : item.title,
        'link' : item.link
      }
      stories.append(story)
  return stories

print(get_titles('aldi'))

Tags: 脚本searchgettitlelinkitem新闻stories
3条回答

你可以试试下面的方法

以dict列表的形式获取数据,循环列表并将每个条目写入文件

from pygooglenews import GoogleNews

gn = GoogleNews(country = 'IE')

def get_titles(search):
  stories = []
  search = gn.search(search)
  newsitem = search['entries']
  for item in newsitem:
      story = {
        'title' : item.title,
        'link' : item.link
      }
      stories.append(story)
  return stories

stories = get_titles('aldi')
with open('stories.csv','w',encoding='utf-8') as f:
    f.write('title,link\n')
    for s in stories:
        f.write(f'{s["title"]},{s["link"]}\n')

stories.csv

title,link
Aldi to trial first checkout-free supermarket - BreakingNews.ie,https://www.breakingnews.ie/business/aldi-to-trial-first-checkout-free-supermarket-1186611.html
Green light given to plans for new Aldi store in Ennis - Clare Champion,https://clarechampion.ie/green-light-given-to-plans-for-new-aldi-store-in-ennis/
Kildare woman scoops up top prize at Aldi's National Brown Bread Baking Competition 2021 - Leinster Leader,https://www.leinsterleader.ie/news/local-news/666996/kildare-woman-scoops-up-top-prize-at-aldi-s-national-brown-bread-baking-competition-2021.html
Aldi to open new shops in Co Mayo and Co Galway - RTE.ie,https://www.rte.ie/news/business/2021/0909/1245582-two-new-aldi-stores-for-connacht/
Aldi, Lidl and Tesco Ireland customers reveal their favourite 'hidden gems' with some unknown bargains - Irish Mirror,https://www.irishmirror.ie/lifestyle/aldi-lidl-tesco-ireland-customers-25021723
"It's a massive boost for us." Grow with Aldi winners - Newstalk,https://www.newstalk.com/podcasts/highlights-from-the-pat-kenny-show/its-a-massive-boost-for-us-grow-with-aldi-winners
Gourmet sausage, burger sauce, cookies: Winners of Grow with Aldi announced - Agriland,https://www.agriland.ie/farming-news/gourmet-sausage-burger-sauce-cookies-winners-of-grow-with-aldi-announced/
Elderly Clare couple fined for refusing to wear masks in Aldi - Clare Champion,https://clarechampion.ie/elderly-clare-couple-fined-for-refusing-to-wear-masks-in-aldi/
Tesco, Aldi, M&S and Morrisons supermarkets acquired by real estate investment giant in £113.1m deal - Business Live,https://www.business-live.co.uk/commercial-property/tesco-aldi-ms-morrisons-supermarkets-21616148
Aldi And IRFU Launch New Cookbook In Support Of Barnardos - Irish Rugby,https://www.irishrugby.ie/2021/09/12/aldi-and-irfu-launch-new-cookbook-in-aid-of-barnardos/
Aldi unveils plan to build store in Thames Ditton with 50 jobs created - Surrey Live,https://www.getsurrey.co.uk/news/surrey-news/aldi-unveils-plan-build-store-21625481
Aldi Salad Dressing Is Getting Recalled Due To Contamination - Delish.com,https://www.delish.com/food-news/a37665205/aldi-salad-dressing-recall-september-2021/
...

您可以使用CSV模块在从搜索中提取行时写入这些行

from pygooglenews import GoogleNews
import csv

gn = GoogleNews(country = 'IE')

def write_csv(filename, search):
    search = gn.search(search)
    with open(filename, "w", newline="") as fileobj:
        csv.writer(fileobj).writerows((item.title, item.link) 
          for item in search['entries'])

write_csv('output.csv', 'aldi')

一种简单(但繁重)的方法是使用pandas,它可以轻松地将字典列表转换为数据帧

import pandas as pd

pd.DataFrame(stories).to_csv("result_list.csv")

这里回答了内置方式:How do I convert this list of dictionaries to a csv file?

import csv

with open("results_list.csv", "w", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=stories[0].keys())
    writer.writeheader()
    writer.writerows(stories)

相关问题 更多 >