【发布时间】:2021-05-29 20:52:24
【问题描述】:
我正在 Python 中使用类和 ElementTree
我有一个从 Yahoo XML 获取新闻的功能,包括标题、公开日期和链接,然后我将它们存储到一个列表中:
import urllib.request
import xml.etree.ElementTree as ET
def get_contents():
url = 'https://www.yahoo.com/news/rss'
with urllib.request.urlopen(url) as response:
data = response.read()
root = ET.fromstring(data)
channel = root[0]
titles = [nt.text for nt in channel.iter('title')]
dates = [pd.text for pd in channel.iter('pubDate')]
links = [nl.text for nl in channel.iter('link')]
contents = [[titles[i], dates[i], links[i]] for i in range(len(titles) - 1)]
return contents
我还有一个 Content 类,其中包含 init 函数来声明标题、公开日期和链接。另外,如果我创建对象,我有 str 函数来获取对象的格式字符串:
class Content():
def __init__(self, title, link, pub_date):
# TODO: your code here
self.title = title
self.link = link
self.pub_date = pub_date
def __str__(self):
# TODO: your code here
return self.title + '. (' + self.pub_date + ')' + '\n' + self.link
现在,我想通过 Content() 类创建一个对象,并通过我拥有的列表(在 get_contents() 函数返回)获取标题、公开日期和链接,例如:
感谢您的帮助。
【问题讨论】:
标签: python list class elementtree