Last active
January 25, 2019 19:33
-
-
Save tmattio/191c5528395bdae7250ab5374da223a4 to your computer and use it in GitHub Desktop.
Convert HAR files to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import json | |
import csv | |
def truncate(s: str, threshold: int = 120): | |
return (s[:threshold] + "..") if len(s) > threshold else s | |
def get_headers(): | |
return ("URL", "Time in Seconds", "Payload", "Response") | |
def get_data_from_entry(entry): | |
try: | |
payload = entry["request"]["postData"]["text"] | |
except KeyError : | |
payload = "" | |
return { | |
"URL": entry["request"]["url"], | |
"Time in Seconds": "{0:.2f}".format(entry["time"] / 1000), | |
"Payload": payload, | |
"Response": truncate(entry["response"]["content"]["text"]), | |
} | |
def parse_har_file(har_file): | |
har_data = open(har_file, "rb").read() | |
skip = 3 if "\xef\xbb\xbf" == har_data[:3] else 0 | |
har = json.loads(har_data[skip:]) | |
return har["log"]["entries"] | |
if "__main__" == __name__: | |
if len(sys.argv) < 2: | |
print("Usage: %s <har_file>" % sys.argv[0]) | |
sys.exit(1) | |
har_file = sys.argv[1] | |
entries = parse_har_file(har_file) | |
data = map(get_data_from_entry, entries) | |
with open("result.csv", "w") as fp: | |
writer = csv.DictWriter(fp, fieldnames=get_headers()) | |
writer.writeheader() | |
for row in data: | |
writer.writerow(row) | |
print("Done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment