首页 > 解决方案 > 属性错误:“list”对象在使用 pygooglenews 时没有属性“strftime”

问题描述

我正在尝试使用 pygooglenews 获取新闻文章的标题和发布时间。我希望能够在 15 天内获得每日文章,我编写了下面的代码来指定开始和结束日期。但我收到一条错误消息,提示“列表对象没有属性 strftime”

import datetime
from datetime import date
gn = GoogleNews(lang = 'en', country = 'US')
start_date = datetime.date(2021, 9, 1)
end_date = datetime.date(2021,9,14)
delta = datetime.timedelta(days=1)
search = gn.search('AAPL', from_=date.strftime('%Y-%m-%d'), to_=(date+delta).strftime('%Y-%m-%d'))
#search = gn.search('AAPL', when = '12m')
#search = gn.search('AAPL', from_=datetime.date.strftime('2016-09-14'), to_=datetime.date.strftime('2021-09-14'))

links=[]
for item in search['entries']:
  links.append(item.title)

date=[]
for item in search['entries']:
  date.append(item.published)
import pandas as pd
d={"Headline": links, "Timestamp": date}
df = pd.DataFrame(d)
df.to_csv('/content/drive/MyDrive/google_news_Apple_1y.csv')

错误

> Full error stacktrace: TypeError                                
> Traceback (most recent call last) <ipython-input-22-f1b0926565ea> in
> <module>()
>       3 end_date = datetime.date(2021,9,14)
>       4 delta = datetime.timedelta(days=1)
> ----> 5 search = gn.search('AAPL', from_=date.strftime('%Y-%m-%d'), to_=(date+delta).strftime('%Y-%m-%d'))
>       6 #search = gn.search('AAPL', when = '12m')
>       7 #search = gn.search('AAPL', from_=datetime.date.strftime('2016-09-14'),
> to_=datetime.date.strftime('2021-09-14'))
> 
> TypeError: descriptor 'strftime' requires a 'datetime.date' object but
> received a 'str

我知道我可能不得不遍历“列表”搜索,但我无法弄清楚如何。请帮我解决这个问题,谢谢!

标签: pythondatetimeweb-scrapingpygooglenews

解决方案


我想你的意思是

search = gn.search('AAPL', from_=start_date.strftime('%Y-%m-%d'), to_=(start_date+delta).strftime('%Y-%m-%d'))

或者也许使用end_date,但无论如何都不是date


推荐阅读