You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本无法输出匹配TOOL01/TOOL02的<td>内容,无报错无结果

脚本无输出问题排查与修复

核心错误:tr标签查找语法错误

你写的table.find_all('<tr>')是错误用法,BeautifulSoup查找HTML标签时,只需传入不带尖括号的标签名,改成table.find_all('tr')即可——这是导致脚本找不到任何行、无输出的直接原因。

可选优化点

  1. 验证请求是否成功
    原代码没检查HTTP请求状态,建议在requests.get(url)后添加一行:

    response.raise_for_status()
    

    这样如果请求返回4xx/5xx错误,会直接抛出异常,方便排查网络或页面访问问题。

  2. 优化文本匹配逻辑
    单元格文本可能包含空格、换行符,直接用cell.get_text()可能导致匹配失效,建议加上strip=True清除空白;如果需要忽略大小写,还可以统一转成大写:

    if any('TOOL01' in cell.get_text(strip=True).upper() or 'TOOL02' in cell.get_text(strip=True).upper() for cell in cells):
    
  3. 避免依赖私有属性
    原代码用p._rows判断表格是否有数据,_rows是PrettyTable的内部私有属性,版本更新可能失效,建议改用公开属性:

    if len(p.rows) > 0:
    

修复后的完整代码

import requests
from bs4 import BeautifulSoup
from prettytable import PrettyTable

def find_sort_in_urls(url_list, custom_columns):
    for url in url_list:
        try:
            response = requests.get(url)
            response.raise_for_status()  # 验证请求是否成功
            soup = BeautifulSoup(response.text, 'html.parser')
            p = PrettyTable()
            p.field_names = custom_columns

            for table in soup.find_all('table'):
                # 修正tr标签查找方式
                for row in table.find_all('tr'):    
                    cells = row.find_all('td')
                    # 处理空白字符,优化匹配逻辑
                    if any('TOOL01' in cell.get_text(strip=True) or 'TOOL02' in cell.get_text(strip=True) for cell in cells):
                        p.add_row([td.get_text(strip=True) for td in cells])                     
                          
            # 用公开属性判断是否有行数据
            if len(p.rows) > 0:
                print(f'{p}\n')

        except requests.exceptions.RequestException as e:
            print(f"访问{url}出错: {e}")

# 要检查的URL列表
urls = ["http://path/toolPM.php"]

# 自定义列名
custom_columns = ["Location", "Entity", "Entity Type", "Weekly PM"]

find_sort_in_urls(urls, custom_columns)

input("按ENTER键继续")

内容的提问来源于stack exchange,提问作者user19568486

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:00:10