如何使用提要解析器 python 解析 xml 提要?

How to parse a xml feed using feed parser python?

我正在尝试使用 feedparser 解析 python 中的提要。但我得到的只是 None 返回。我不确定我错过了什么。这是我的代码:

import feedparser

def rss(self):
    rss = 'https://news.google.com/news?q=fashion&output=rss'
    feed = feedparser.parse(rss)
    for key in feed.entries: 
        return key.title

如果您认为有更好的rss/xml提要解析。请告诉我。 (我是 python 的新手)

print(key) 显示 none print(len(feed.entries)) 也显示 none

print(feed)
{'feed': {}, 'entries': [], 'bozo': 1, 'bozo_exception': URLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)}

print(feedparser)
<module 'feedparser' from '/Users/User_name/python-projects/my_env/lib/python3.6/site-packages/feedparser.py'>

试试下面的基本代码,它对我来说效果很好,当我 运行 它时,它在提要中给了我 10 个项目。

  1. 从 pip
  2. 安装 feedparser
pip install feedparser
  1. 用法
import urllib2
import feedparser

url = "https://news.google.com/news?q=fashion&output=rss"
response = urllib2.urlopen(url).read()

print response

d = feedparser.parse(response)
print len(d.entries)
for item in d.entries:
    print "------"
    print item.title
    if 'subtitle' in item:
        print item.subtitle
    print item.link
    print item.description
    print item.published
    print item.id
    print item.updated
    if 'content' in item:
        print item.content

或者,粘贴您 运行 的完整代码,我会看一看。

发现问题实际上是通过添加 ssl._create_default_https_context = ssl._create_unverified_context.

解决的 SSL 握手问题

对于面临此问题的任何其他人。完整代码为:

import feedparser
import ssl
if hasattr(ssl, '_create_unverified_context'):
    ssl._create_default_https_context = ssl._create_unverified_context
rss = 'https://news.google.com/news?q=fashion&output=rss'
feed = feedparser.parse(rss)

print(feed)