从网站解析XML并保存代码?

2024-09-27 22:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个类似 http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio 并将其保存在另一个xml或csv文件中

我试过这个:

import urllib.request 
web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio")
str_data = web_data.read()
try:
   f = open("file.xml", "w")
   f.write(str(str_data))
   print("SUCCESS")
except:
   print("ERROR")

但在保存的XML中,数据位于每个元素“\n”和开头的“b”之间

如果没有所有的“n”和“b”,如何保存XML数据


Tags: orgresthttpdataservicexmlurllibops
2条回答

如果以二进制模式编写xml文件,则不需要先将读取的数据转换为字符串。另外,如果一次处理一行数据,应该可以解决'\n'问题。代码的逻辑结构也可以更好一些,如下所示:

import urllib.request

web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services"
                                  "/published-data/publication"
                                  "/docdb/EP1000000/biblio")
data = web_data.read()
with open("file.xml", "wb") as f:
    for line in data:
        try:
            f.write(data)
        except Exception as exc:
            print('ERROR')
            print(str(exc))
            break
    else:
        print('SUCCESS')

read()bytes的形式返回数据,但您可以保存数据,而无需转换为str()。您必须以byte模式打开文件-"wb"-并写入数据

import urllib.request

web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio")
data = web_data.read()

try:
   f = open("file.xml", "wb")
   f.write(data)
   print("SUCCESS")
except:
   print("ERROR")

顺便说一句:要将bytes转换为string/unicode,您必须使用ie.decode('utf-8')。 如果您使用str(),那么Python使用自己的方法来创建字符串,并添加b"来通知您的data中有bytes

相关问题 更多 >

    热门问题