Aiming at the problems of low efficiency and poor real-time performance in the printed circuit board (PCB) defect detection, a PCB defect detection method based on the improved YOLOv5 is proposed, which integrates the module of multiscale detection, attention mechanism and multi-branch. A shallow detection layer is added to detect smaller defect targets and fused with features of the deep network. An optimized anchor clustering method was used to obtain a more suitable size for the dataset. The Convolutional Block Attention Module (CBAM) is introduced to reweight and assign important feature channels to learn more valuable features. The re-parameterization convolution (RepConv) module is integrated to decouple the multi-branch training model into a single-way inference model by structural re-parameterization, which improves the model’s training performance and reduces inference time. The experimental results show that the detection accuracy of the proposed algorithm reaches 98.3% on the extended dataset, which is 3.4% higher than that of the original algorithm. At the same time, a real-time detection performance of 63 FPS is achieved, which satisfies the detection requirements of the PCB.