如何用BeautifulSoup获取指定服务所在表格对象并提取对应价格?
问题
需要完成以下操作:
- 检查指定字符串对应的服务是否可用
- 若可用则获取其对应价格
已知价格存储在未知名称的table中,已用BeautifulSoup通过变量strServiceVersion查找包含该字符串的列,代码如下:
arrDataCell = soup.find_all('td', text=strServiceVersion) if len(arrDataCell)>0: #found data cell with given string print("\nPrint whole data cell: ") print(arrDataCell) print("\nPrint parent of the 1st data cell: ") #print below print(arrDataCell[0].parent())
执行后确认服务名称存在于表格中,第一个数据单元格的父元素输出为:
[<td class="column-1"> Some_Text_1</td>, Some_Text_2, <td class="column-2">Price_1</td>, Price_2]
已知表格有两列,类名为column-1和column-2,希望获取表格对象以按行和列遍历提取数据,求实现方法或其他解决方案。
解决方案
方法一:回溯获取表格并遍历
既然已经定位到包含目标字符串的td元素,直接通过它的父节点往上找最接近的table标签即可拿到表格对象,之后就能按行和列遍历:
# 找到目标单元格后 if arrDataCell: # 获取目标单元格所在的行 target_row = arrDataCell[0].parent # 获取该行所在的表格 target_table = target_row.find_parent('table') # 遍历表格的每一行 for row in target_table.find_all('tr'): # 获取当前行的所有单元格 cells = row.find_all('td') if len(cells) >=2: # 提取column-1和column-2的内容 service_name = cells[0].get_text(strip=True) price = cells[1].get_text(strip=True) # 判断是否是目标服务 if service_name == strServiceVersion.strip(): print(f"服务可用,价格:{price}")
方法二:直接从目标行提取价格(高效)
如果只需要目标服务的价格,不需要遍历整个表格,可直接从找到的单元格所在行提取对应列的内容:
if arrDataCell: target_row = arrDataCell[0].parent # 定位该行内的column-2单元格 price_cell = target_row.find('td', class_='column-2') if price_cell: price = price_cell.get_text(strip=True) print(f"服务可用,价格:{price}")
方法三:遍历所有表格匹配数据(备选)
如果不确定目标表格位置,可遍历页面中所有表格,逐个检查每一行内容:
# 遍历页面所有表格 for table in soup.find_all('table'): for row in table.find_all('tr'): service_cell = row.find('td', class_='column-1') price_cell = row.find('td', class_='column-2') if service_cell and price_cell: service_name = service_cell.get_text(strip=True) if service_name == strServiceVersion.strip(): print(f"服务可用,价格:{price_cell.get_text(strip=True)}") # 找到后退出循环,提升效率 break else: continue break
内容的提问来源于stack exchange,提问作者Hronic
相关产品推荐
相关产品推荐

