Both cruising ability and safety should be considered in the 3D inspection path planning of agricultural unmanned aerial vehicles (UAVs). Specific to a complex working environment, the 3D inspection environment of agricultural UAVs was simulated through terrain modeling and threat modeling. First, the dynamic constraints of flight approaching rate and response time were added to the threat cost, and the 3D mission space model and flight path cost function were constructed considering the influence of UAVs’ turning performance. Second, the offset estimation strategy, variable spiral search strategy, quasi-reverse learning strategy and dimension-by-dimension mutation strategy were introduced into the dung beetle optimizer (DBO) algorithm to improve the global optimization ability and convergence rate of the algorithm. By establishing a three-dimensional trajectory planning model for unmanned aerial vehicles, the trajectory planning is transformed into a multi-objective function optimization problem, and an improved algorithm is used to solve the three-dimensional trajectory planning of unmanned aerial vehicles. The fitness is evaluated by considering the objective function of trajectory cost, terrain cost, and danger level, and the trajectory planning is iteratively optimized. The results indicate that the proposed improved dung beetle algorithm for trajectory planning has lower overall cost and stability in adapting to different complex terrain environments.