【问题标题】:Attribute error: 'list' object has no attribute 'strftime' while using pygooglenews属性错误:“list”对象在使用 pygooglenews 时没有属性“strftime”
【发布时间】:2021-09-22 05:38:38
【问题描述】:

我正在尝试使用 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

我知道我可能需要遍历“列表”搜索,但我不知道如何进行。请帮我解决这个问题,谢谢!

【问题讨论】:

  • 在您的代码示例中,变量date 未定义,您能否澄清一下?另外,我很难理解您截取的错误与您的关系如何 - 在您的示例中找不到类似的错误(基本上看起来不错)。
  • 请不要张贴代码、错误、输入、输出等图片。

标签: python datetime web-scraping pygooglenews


【解决方案1】:

我想你是说

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

或者可能使用end_date,但无论如何不要使用date

【讨论】:

  • 是的,这是错误,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2013-11-22
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多