gpt4 book ai didi

Python feedparser 返回第一个条目中第一个媒体项的 URL

转载 作者:行者123 更新时间:2023-12-01 04:20:47 26 4
gpt4 key购买 nike

我是第一次使用 python,我有点卡住了。

使用 feedparser 解析 RSS feed,我想获取条目 0 的第一个媒体项的 URL 并将其加载到变量中。

下面的代码似乎可以工作,但我必须按两次 Enter 才能运行它,它会返回条目 0 中所有媒体项目的 URL,其中我只需要第一个 (16x9) 图像 URL。

>>> import feedparser
>>> d = feedparser.parse(http://www.abc.net.au/news/feed/45910/rss)
>>> for content in d.entries[0].media_content: print content['url']

-link to where i got the code above

RSS XML:

            <media:group>
<media:description>French fighter jets take off to drop bombs on the Islamic State stronghold of Raqqa in Syria. (Supplied)</media:description>
<media:content url="http://www.abc.net.au/news/image/6943630-16x9-2150x1210.jpg" medium="image" type="image/jpeg" width="2150" height="1210"/>
<media:content url="http://www.abc.net.au/news/image/6943630-4x3-940x705.jpg" medium="image" type="image/jpeg" width="940" height="705"/>
<media:content url="http://www.abc.net.au/news/image/6943630-3x2-940x627.jpg" medium="image" type="image/jpeg" width="940" height="627" isDefault="true"/>
<media:content url="http://www.abc.net.au/news/image/6943630-3x4-940x1253.jpg" medium="image" type="image/jpeg" width="940" height="1253"/>
<media:content url="http://www.abc.net.au/news/image/6943630-1x1-1400x1400.jpg" medium="image" type="image/jpeg" width="1400" height="1400"/>
<media:thumbnail url="http://www.abc.net.au/news/image/6943630-4x3-140x105.jpg" width="140" height="105"/>
</media:group>

在 python 中运行时看起来像这样:

>>> for content in d.entries[0].media_content: print content['url']
...
http://www.abc.net.au/news/image/6943630-16x9-2150x1210.jpg
http://www.abc.net.au/news/image/6943630-4x3-940x705.jpg
http://www.abc.net.au/news/image/6943630-3x2-940x627.jpg
http://www.abc.net.au/news/image/6943630-3x4-940x1253.jpg
http://www.abc.net.au/news/image/6943630-1x1-1400x1400.jpg
>>>

最佳答案

快速回答:

url = d.entries[0].media_content[0]['url']

d.entries[n].media_content 是一个充满字典的列表,因此您只需获取该列表中的第一项,并将“url”处的值存储在变量中。

这是它在 Python shell 中的样子:

>>> import feedparser
>>> d = feedparser.parse("http://www.abc.net.au/news/feed/45910/rss")
>>> url = d.entries[0].media_content[0]['url']
>>> print url
http://www.abc.net.au/news/image/6943798-16x9-2150x1210.jpg

关于Python feedparser 返回第一个条目中第一个媒体项的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33727266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com