A drug target is usually a protein, and a protein is a long chain of building blocks folded into a specific three-dimensional shape. That folding creates pockets and ridges on the protein's surface — places where a small molecule can settle in and be held by the same kinds of weak attractive forces that hold the protein's own shape together.
A molecule that acts on the target is called a binder, and the fit is the whole point. When a molecule settles into a pocket, it can block the spot where the protein's normal partner would have attached, or it can hold the protein in a shape that no longer does its job. Either way, the protein's activity changes, and that change is what the medicine is for.
This is why the search is not random. Scientists do not look for any molecule; they look for a molecule whose shape and chemical character match one particular pocket on one particular protein. A molecule that fits a pocket on the wrong protein may still change something in the body, which is exactly how unwanted side effects arise.