使用BeautifulSoup解析表格时tr.findall('td')报NoneType不可调用错误求助
报错原因
- 核心拼写错误:BeautifulSoup提供的查找多个节点的方法是
find_all(),你的代码里写成了findall(),缺少下划线,调用不存在的属性会返回None,尝试对None执行调用操作就触发了'NoneType' object is not callable的错误 - 缺失依赖导入:代码中使用了
requests.get()但没有导入requests库,拼写问题修复后会触发新的导入报错 - 代码缩进错误:你提供的代码中循环体、变量赋值、打印语句都没有正确缩进,Python依靠缩进判断代码块归属,缩进错误也会导致运行异常
修复后的完整可运行代码
import requests from bs4 import BeautifulSoup headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"} response = requests.get("https://shubhamsayon.github.io/python/demo_html", headers = headers) webpage = response.content soup = BeautifulSoup(webpage, "html.parser") for tr in soup.find_all('tr'): topic = "TOPIC: " url = "URL: " # 修正拼写错误:findall改为find_all values = [data for data in tr.find_all('td')] for value in values: print(topic, value.text) topic = url
修复后运行会依次输出页面表格中每个单元格的分类和对应内容,不会再触发类型错误。
内容的提问来源于stack exchange,提问作者Andylannister
相关产品推荐
相关产品推荐

