所以我有一个CSV文档,每行都有元数据,XPATH和Regex字符串。该脚本使用xpath迭代API请求,然后我想使用存储在CSV中的正则表达式与该xpath一起搜索API结果中的内容。我的问题是如何将CSV行中的数据用作文字正则表达式搜索字符串,例如r'^\w{2}.+'
与要搜索的字符串。
with open(rules, 'r+') as rulefile:
rreader = csv.DictReader(rulefile)
for row in rreader:
for ip, apikey in keydict.iteritems():
rulequery = {'type': 'config', 'action': 'get', 'key': apikey, 'xpath': row["xpath"]}
rrule = requests.get('https://' + ip + '/api', params = rulequery, verify=False)
rrex = re.compile('{}'.format(row["regex"]), re.MULTILINE)
for line in rrule.text:
config = rrex.findall(line)
print(config)
答案 0 :(得分:1)
所以我想我可能找到了一个解决方案,虽然我不确定它是最好的......如果有人有更好的方法,请打开帮助。
with open(rules, 'r+') as rulefile:
rreader = csv.DictReader(rulefile)
for row in rreader:
for ip, apikey in keydict.iteritems():
regex = row["regex"]
rulequery = {'type': 'config', 'action': 'get', 'key': apikey, 'xpath': row["xpath"]}
rrule = requests.get('https://' + ip + '/api', params = rulequery, verify=False)
config = re.search(regex, rrule.text)
print rrule.text[config.start():config.end()]