Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何解析XML文件并从Python中获取其数据_Python_Xml - Fatal编程技术网

如何解析XML文件并从Python中获取其数据

如何解析XML文件并从Python中获取其数据,python,xml,Python,Xml,我在以下web服务中有一个帐户:“” 我需要解析它,并获取XML文件中每个项目的标题和日期值 我已尝试将数据获取到xml文件,并尝试对其进行解析,但我看到所有空白值: import requests import xml.etree.ElementTree as ET response = requests.get('https://news.google.com/news/rss/?ned=us&hl=en') with open('text.xml','w') as xmlfile

我在以下web服务中有一个帐户:“”

我需要解析它,并获取XML文件中每个项目的标题和日期值

我已尝试将数据获取到xml文件,并尝试对其进行解析,但我看到所有空白值:

import requests
import xml.etree.ElementTree as ET

response = requests.get('https://news.google.com/news/rss/?ned=us&hl=en')
with open('text.xml','w') as xmlfile:
    xmlfile.write(response.text)

with open('text.xml','rt') as f:
    tree = ET.parse(f)

for node in tree.iter():
    print (node.tag, node.attrib)
我不确定我会错在哪里。我必须以某种方式提取XML中每个项目的标题和发布日期的值


感谢您提前回复。

@Ilja Everilä是对的,您应该使用feedparser。 当然,不需要编写任何xml文件。。。除非你想存档

我并没有真正得到您所期望的输出,但类似的东西是有效的(Python 3)

要将其显式打印为utf8字符串,请使用:

print([(d['entries'][i]['title'].encode('utf8'), d['entries'][i]['tags'][0]['term'].encode('utf8')) for i in range(len(d['entries']))])

也许,如果您显示预期的输出,我们可以帮助您从解析器中获取正确的内容。

,只需在feedparser.parse(response.text.entries)中为e添加
[(e.title,e.published)]
。我回答了您的问题吗?是的,您回答了。。。非常感谢丽嘉!不清楚,我?丽嘉?因此,请接受我的回答。我在这里遇到了一个奇怪的问题:回溯(最近一次调用):文件“Hacker.py”,第8行,打印((d['entries'][i]['title'],d['entries'][i]['published'])文件“C:\Users\bhatsubh\AppData\Local\Programs\Python\Python35\lib\encodings\C p437.py”,第19行,在encode return codes.charmap\u encode中(输入、自身错误、编码映射)[0]UnicodeEncodeError:“charmap”编解码器无法对位置50中的字符“\u2014”进行编码:字符映射到我的主要目的是从用户处获取日期时间值,并使用它检索该日期后发布的帖子此错误是由于字符串编码问题造成的,这是因为python试图将字节表示为ascii字符串。请尝试:
打印([(d['entries'][i]['title'].encode('utf8'),d['entries'][i]['tags'][0]['term'].encode('utf8'))以显示范围内的i(len(d['entries']))]
print([(d['entries'][i]['title'].encode('utf8'), d['entries'][i]['tags'][0]['term'].encode('utf8')) for i in range(len(d['entries']))])