[英]lxml etree cleanup_namespaces returns None instead of cleaned tree
我写了一个小的 class 用于抓取包含文件夹内一些文档的网页,所有这些都托管在 S3 上。 我将响应转换为 XML 树,我需要从前缀 URL 中清除每个元素。
这是代码和问题:
import requests
from lxml import etree
class scraper():
def __init__(self, BASE_URL, headers):
self.BASE_URL = BASE_URL
self.headers = headers
self.URL = self.BASE_URL + '?delimiter=/'
def clean_root(self, root):
"Needed to clean the URL prefix in front of each XML element"
for elem in root.getiterator():
elem.tag = etree.QName(elem).localname
return etree.cleanup_namespaces(root)
def get_root_folder_names(self):
"Retrieve the folders"
res = requests.get(self.URL, headers=self.headers)
root = etree.XML(res.content)
print(f"{root}") # prints: "root: <Element {http://s3.amazonaws.com/doc/2016-11-11/}ListBucketResult at 0x8f87b456e441>"
print(f"{self.clean_root(root)}") # prints: "None", where it must prints "<Element ListBucketResult at 0x8f87b456e441>"
叫它:
myInstance = scraper(BASE_URL, headers)
myInstance.get_root_folder_names()
如果我从get_root_folder_names
function 调用clean_tree(root)
,则结果为None
,就好像它从未应用过一样。 但是root
在调用此 function 之前确实存在,因为它已正确打印。 我从这里得到启发: https://www.kite.com/python/answers/how-to-call-an-instance-method-in-the-same-class-in-python
我究竟做错了什么?
我还尝试在没有 self 的情况下使用clean_root
function self.
但是,当我从get_root_folder_names
function 调用它时,我得到了NameError: name 'clean_tree' is not defined
。
问题不在于从其他函数调用函数。 它将纯函数与具有副作用的函数混淆了。
function cleanup_namespaces
返回None
。 它修改树,而不是创建一个新树(这就像初学者经常遇到的问题list.sort
)。
将clean_root
function 的末尾更改为:
etree.cleanup_namespaces(root)
return root
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.