简体   繁体   English

从格式类似于 Python 中的 JSON 文件的列表中提取值

[英]Extract value from a list formatted like a JSON file in Python

I have a function that returns an image URL from an RSS feed (I'm using feedparser).我有一个从 RSS 提要返回图像 URL 的函数(我使用的是 feedparser)。 The problem is that it returns a strange formatted list.问题是它返回一个奇怪的格式化列表。

My feed has a key called media_content .我的提要有一个名为media_content的键。 The code used to access it is用于访问它的代码是

import feedparser
NewsFeed = feedparser.parse("https://thegroovecartel.com/feed/")
entry = NewsFeed.entries[0]
post_image = entry.media_content

Now, for some reason post_image is a list of 1 element formattes as:现在,由于某种原因 post_image 是 1 个元素格式的列表:

[{'url': 'https://thegroovecartel.com/i1.wp.com/thegroovecartel.com/wp-content/uploads/2020/10/KAYYA.jpg?fit=300%2C237&ssl=1', 'medium': 'image'}]

Now, I can't understand how to access the actual URL field to have https://thegroovecartel.com/i1.wp.com/thegroovecartel.com/wp-content/uploads/2020/10/KAYYA.jpg?fit=300%2C237&ssl=1 as a string into a variable.现在,我无法理解如何访问实际的 URL 字段以拥有https://thegroovecartel.com/i1.wp.com/thegroovecartel.com/wp-content/uploads/2020/10/KAYYA.jpg?fit=300%2C237&ssl=1作为字符串转化为变量。

post_image = [{'url': 'https://thegroovecartel.com/i1.wp.com/thegroovecartel.com/wp-content/uploads/2020/10/KAYYA.jpg?fit=300%2C237&ssl=1', 'medium': 'image'}]
print(post_image[0]['url'])

Result结果

https://thegroovecartel.com/i1.wp.com/thegroovecartel.com/wp-content/uploads/2020/10/KAYYA.jpg?fit=300%2C237&ssl=1

You've got to treat post_image as a list, assessing its first element (ie element with index 0), gives you the dictionary that contains your image's attribute您必须将post_image视为一个列表,评估其第一个元素(即索引为 0 的元素),为您提供包含图像属性的字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM