Python 使用re.findall时出现类型错误
我试图从XML文档中提取IP地址,下面是相关代码Python 使用re.findall时出现类型错误,python,regex,ipv4,Python,Regex,Ipv4,我试图从XML文档中提取IP地址,下面是相关代码 def traverseNode(node): output = node.find(****) if output is not None: ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}', output) for ip in ips: print ip for child in node.getchildren():
def traverseNode(node):
output = node.find(****)
if output is not None:
ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}', output)
for ip in ips:
print ip
for child in node.getchildren():
traverseNode(child)
此代码返回错误TypeError:应为字符串或缓冲区
你知道这是什么原因吗?提前感谢您的帮助。请确保要re.findall的第二个参数(pattern,arg)是字符串。可以使用str(arg)确保将字符串放入re.findall 因此解决方案是将线路更改为:
output=node.find('**').text输出的类型是什么?我通常会猜测它是另一个
节点
或其他东西,而不是字符串或缓冲区…find
返回节点对象。您可能希望在output.text
或output.attrib
或类似的内容中搜索IP是的,我需要将output设置为nod.find().text.IMO,这很容易出错,因为如果找不到匹配项,它将抛出一个AttributeError:NoneType对象没有属性text
。继续按原样做,但使用re
doips=re.findall(r'[0-9]+(?:\[0-9]+){3},output.text)