我通过TheGuardian.search_content()
和TheGuardian.data_to_csv()
方法使用Guardian Python API。第一个返回一个名为json_content
的字典。第二个,遍历json_content并将其内容写入CSV文件。我的问题是,为什么TheGuardian.data_to_csv()
方法会收到<class 'script_guardian.TheGuardian'>
而不是<class 'dict'>
?
如果我理解正确,TheGuardian.data_to_csv()
只会收到TheGuardian类的实例。它与我使用的方法有什么关系?例如,抽象,静态或类方法
步骤:
>>> from script_guardian import TheGuardian
>>> tg = TheGuardian('2016-01-01', '2018-01-01')
>>> json_content = tg.search_content('education', 'relevance', 'education')
>>> json_content
<bound method Content.get_content_response of <theguardian.theguardian_content.Content object at 0x7f7bb9764c88>>
>>> type(json_content)
<class 'method'>
如何让search_content返回而不是方法本身?
我的完整代码:
import requests
from theguardian import theguardian_content
import csv
class TheGuardian:
def __init__(self, from_date='2016-01-01', to_date='2018-01-01'):
self.from_date = from_date
self.to_date = to_date
def search_content(self, content='education', page_size=10, order_by='relevance',
api_key='test'):
self.content = content
self.page_size = page_size
self.order_by = order_by
self.api_key = api_key
# create content
params = {
'from-date': self.from_date,
'to_date': self.to_date,
'order-by': self.order_by,
'page-size': self.page_size,
'q': self.content,
'api': self.api_key
}
# create content
content = theguardian_content.Content(**params)
pdb.set_trace()
json_content = content.get_content_response()
# actual response
return json_content
def data_to_csv(self, json_content):
self.json_content = json_content
with open('guardian_data.csv','w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(["webUrl", "webPublicationDate", "webTitle", "sectionName",
"apiUrl", "id", "isHosted", "sectionId", "type", "pillarId", "pillarName"])
for result in json_content['response']['results']:
writer.writerow(
result["webUrl"],
result["webPublicationDate"],
result["webTitle"],
result["sectionName"],
result["apiUrl"],
result["id"],
result["isHosted"],
result["sectionId"],
result["type"],
result["pillarId"],
result["pillarName"]
)
答案 0 :(得分:0)
由于您将data_to_csv
作为类方法访问,因此data_to_csv(self,json_content)
不完整。您应该将其定义为tg.data_to_csv(tg.search_content())
并将搜索结果的结果传递给它,例如No test result files matching **\test-results.xml were found.