Python中使用Beautiful Soup提取表格指定数值时的AttributeError问题排查
解决Beautiful Soup提取表格数值时的AttributeError问题
首先来看你遇到的报错原因:AttributeError: 'NoneType' object has no attribute 'find' 是因为 bs.find("td", {"b": "SALÁRIO-BASE"}) 返回了None——这段代码的逻辑完全错了,你在找带有b属性且属性值为"SALÁRIO-BASE"的<td>标签,但实际上网页里的"SALÁRIO-BASE"是<td>内部<b>标签的文本内容,不是<td>的属性,所以根本找不到这个元素。
下面给你两种可行的解决方案:
方案1:直接通过索引定位(适合结构固定的表格)
这种方法简单直接,适合表格行/列顺序不会变化的场景:
import requests from bs4 import BeautifulSoup url = "http://www-sdc/ResultadoSalCon.asp" # 注意设置正确的编码,避免文本乱码 response = requests.get(url) response.encoding = 'utf-8' bs = BeautifulSoup(response.content, "html.parser") # 直接定位到目标表格(页面里有两个class为titulo的元素,一个是p,一个是table,所以明确指定table) target_table = bs.find("table", {"class": "titulo"}) if target_table: # 获取表格所有行,表头是第0行,第一组数据是第1行 rows = target_table.find_all("tr") if len(rows) >= 2: data_row = rows[1] # SALÁRIO-BASE在该行的第2个td(索引1,从0开始计数) salary_cell = data_row.find_all("td")[1] # strip=True去除文本前后的空格 valor = salary_cell.get_text(strip=True) print(valor) # 输出:1.212,00 else: print("未找到目标表格")
方案2:通过表头文本定位列(更健壮的写法)
如果表格的列顺序可能发生变化,这种方法更可靠,先找到"SALÁRIO-BASE"所在的列索引,再提取对应数值:
import requests from bs4 import BeautifulSoup url = "http://www-sdc/ResultadoSalCon.asp" response = requests.get(url) response.encoding = 'utf-8' bs = BeautifulSoup(response.content, "html.parser") target_table = bs.find("table", {"class": "titulo"}) if target_table: # 获取表头行的所有单元格,找到SALÁRIO-BASE的列索引 header_cells = target_table.find("tr").find_all("td") salary_col_idx = None for idx, cell in enumerate(header_cells): if "SALÁRIO-BASE" in cell.get_text(strip=True): salary_col_idx = idx break if salary_col_idx is not None: # 跳过表头,获取所有数据行 data_rows = target_table.find_all("tr")[1:] if data_rows: # 取第一行数据的对应列 salary_val = data_rows[0].find_all("td")[salary_col_idx].get_text(strip=True) print(salary_val) else: print("未找到目标表格")
额外注意点:
- 页面里有两个
class="titulo"的元素,一个是<p>标签,一个是你需要的<table>标签,所以查找时要明确指定table标签,避免找错元素。 - 加上编码设置
response.encoding = 'utf-8'可以避免因编码问题导致的文本乱码或查找失败。
内容的提问来源于stack exchange,提问作者Vet
相关产品推荐
相关产品推荐

