如何用Python提取HTML中指定前缀的属性并生成对应列表?
Python提取HTML指定前缀属性脚本实现
前置准备
首先安装HTML解析依赖库,比正则匹配更稳定,不会因为HTML换行、属性顺序变化出现匹配错误:pip install beautifulsoup4
完整实现代码
from bs4 import BeautifulSoup def extract_attrs_by_prefix(html_content, attr_prefix): soup = BeautifulSoup(html_content, 'html.parser') result = [] # 遍历所有HTML标签 for tag in soup.find_all(True): # 遍历当前标签的所有属性 for attr_name, attr_value in tag.attrs.items(): if attr_name.startswith(attr_prefix): # 处理class这类多值属性的情况 if isinstance(attr_value, list): attr_value = ' '.join(attr_value) result.append(f'{attr_name}="{attr_value}"') return result # 用法示例 if __name__ == '__main__': # 方式1:读取本地HTML文件(推荐,适合大量内容场景) # with open('你的HTML文件路径.html', 'r', encoding='utf-8') as f: # html = f.read() # 方式2:直接传入HTML字符串,适合小片段测试 html = """ 替换为你自己的完整HTML代码 """ # 指定要匹配的属性前缀,可根据需求修改 target_prefix = 'senchatest' res_list = extract_attrs_by_prefix(html, target_prefix) # 控制台输出结果 for item in res_list: print(item) # 需要导出为文件可取消下方注释 # with open('属性提取结果.txt', 'w', encoding='utf-8') as f: # f.write('\n'.join(res_list))
效果验证
使用你提供的示例HTML运行脚本,输出结果如下:
senchatest="mainMenu_game" senchatest="mainMenu_plus"
完全符合预期,即使HTML内有数百个符合要求的属性也可一次性提取完成,导出的文件可直接用于测试场景。
内容的提问来源于stack exchange,提问作者matsi
相关产品推荐
相关产品推荐

