The importance of the UAV path-planning problem lies in ensuring the safe and efficient completion of tasks by UAVs while maximizing resource utilization and minimizing risks. Addressing this issue, a new algorithm named Nonlinear Weighted Whale Optimization Algorithm Improved by Cosine Function for UAV Path Planning (COSWOA) is proposed. This algorithm overcomes the drawbacks of the basic WOA algorithm, such as low solution precision, slow convergence speed, and susceptibility to local optima, by employing a nonlinear dynamic variation strategy based on the cosine function and incorporating nonlinear inertia weights. Simulation results demonstrate that compared to GA, WOA, and GWO algorithms, the COSWOA algorithm can rapidly generate higher-quality paths for UAVs and exhibits better robustness.