Honestly there is no trick other than botting. Unless you happen to know the exact time the last defending pokemon was knocked out (it's 10 minutes from then, you can slot a new one), you can't do anything but keep refreshing.
Be at the gym, ensuring no GPS drift, and keep on clicking the add pokemon button and if it fails try again. Dump anything in and don't bother finding the optimal defender if it is constantly being sniped like that.