为何代码中无法调用findall()方法?TypeError报错解决方案
问题解决:BeautifulSoup处理XML后用ElementTree.findall()报TypeError
错误原因
ET.ElementTree()的构造参数仅接受Element对象或文件对象,你传入的是BeautifulSoup处理后的BeautifulSoup实例,导致ElementTree内部的_root属性为None,调用findall()时触发TypeError: 'NoneType' object is not callable。
修正方案(保留原实现思路)
先通过BeautifulSoup处理XML,再将处理后的内容转为字符串,最后用ET.fromstring()解析成Element对象并构建ElementTree:
from bs4 import BeautifulSoup import urllib.request import xml.etree.ElementTree as ET count = 0 html = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_1591221.xml').read() # 用BeautifulSoup处理XML(可保留你的预处理逻辑) soup = BeautifulSoup(html, 'lxml') # 处理XML用lxml解析器更适配 # 将BeautifulSoup对象转为XML字符串 processed_xml = str(soup) # 解析字符串得到根Element,再构建ElementTree实例 root = ET.fromstring(processed_xml) dp = ET.ElementTree(root) # 正常调用findall获取数据 datas = dp.findall('comment') # 测试输出示例 for comment in datas: print(f"名称: {comment.find('name').text}, 计数: {comment.find('count').text}")
关键修改点
- 将BeautifulSoup的解析器替换为
lxml,处理XML比html.parser兼容性更好 - 通过
str(soup)将BeautifulSoup处理后的内容转为标准XML字符串 - 用
ET.fromstring()解析字符串得到根Element,再传入ET.ElementTree()构建可用实例
内容的提问来源于stack exchange,提问作者Abdallah Faik
相关产品推荐
相关产品推荐

