如何循环处理JSON文件中的xpath 实现索引自增生成序列xpath表达式
错误原因说明
你直接将f-string语法作为字符串存入JSON的方式不可行,JSON只会将其识别为普通文本,运行时不会自动解析替换变量,因此生成的XPath表达式不符合语法规则,触发报错。
方案一:使用模板占位符(推荐)
- 第一步:调整JSON中的XPath存储格式,使用
{index}作为索引占位符:
{ "xpath_template": "//*[@id='idname']/div/[{index}]" }
- 第二步:Python读取模板后通过
str.format()方法动态替换索引:
import json # 读取JSON配置 with open("你的配置文件路径.json", "r", encoding="utf-8") as f: config = json.load(f) xpath_template = config["xpath_template"] # 循环生成XPath for index in range(1, 5): current_xpath = xpath_template.format(index=index) # 此处可直接使用current_xpath执行后续操作 print(current_xpath)
运行后输出结果为:
//*[@id='idname']/div/[1] //*[@id='idname']/div/[2] //*[@id='idname']/div/[3] //*[@id='idname']/div/[4]
方案二:无需修改原有JSON的正则替换方案
如果你不想调整原有JSON的存储结构,可以用正则匹配替换原有固定索引:
import json import re # 读取原有JSON配置 with open("你的配置文件路径.json", "r", encoding="utf-8") as f: config = json.load(f) # 补全XPath前缀 base_xpath = "//*" + config["xpath"] for index in range(1, 5): # 替换末尾的数字索引 current_xpath = re.sub(r"\[\d+\]$", f"[{index}]", base_xpath) print(current_xpath)
内容的提问来源于stack exchange,提问作者otterOtter
相关产品推荐
相关产品推荐

