Skip to content

Instantly share code, notes, and snippets.

@timkrins
Created September 15, 2022 09:45
Show Gist options
  • Save timkrins/229bb64598797b41beb70f43381ad6de to your computer and use it in GitHub Desktop.
Save timkrins/229bb64598797b41beb70f43381ad6de to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
A quick script to filter a HAR file that was saved by Chrome, based on the request URL.
Useful for filtering HAR files to be converted by `har-to-k6` for load testing.
------------------------------------------------------------------------------
MIT License
Copyright (c) 2022 Tim Krins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
import argparse
import re
parser = argparse.ArgumentParser(description='A quick script to filter HAR requests based on a URL regex')
parser.add_argument("--input", required=True, help="The input HAR file")
parser.add_argument("--output", required=True, help="The output HAR file")
parser.add_argument("--regex", required=True, help="The regex to match on the request URL")
args = parser.parse_args()
arg_input = args.input
arg_output = args.output
arg_regex_string = args.regex
# read in our har file
with open(arg_input, "r") as f:
contents = f.read()
# parse the json
json_dict = json.loads(contents)
# now filter out the entries based on the request.url
matched_entries = [entry for entry in json_dict['log']['entries'] if re.search(arg_regex_string, entry['request']['url'])]
# set the entries back to the json dict
json_dict['log']['entries'] = matched_entries
# build the json to save
output_json = json.dumps(json_dict, indent=2)
# write the output json
with open(arg_output, "w") as f:
f.write(output_json)
@sokol8
Copy link

sokol8 commented Aug 7, 2024

great thanks for posting this. you saved me some coding time :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment