本文详解go web爬虫程序因错误使用string()函数转换整数导致http请求url构造失败、文件写入异常的问题,并提供正确转换方式、并发安全实践与完整可运行示例。
本文详解go web爬虫程序因错误使用string()函数转换整数导致http请求url构造失败、文件写入异常的问题,并提供正确转换方式、并发安全实践与完整可运行示例。
在Go语言中,string()类型转换函数仅用于将字节(byte)或rune序列转换为字符串,而不能直接将整数(如int)转为数字字符串。原代码中:
adrr := string("http://torhit.com/torbite/?page=" + string(count))此处 string(count) 是严重错误:count 是 int 类型,string(count) 会将其解释为Unicode码点(例如 count=65 → 'A'),而非字符串 "65";当 count 超出有效Unicode范围(如 count > 0x10FFFF)时,结果为空字符串 "",最终拼接出的URL形如 "http://torhit.com/torbite/?page=" —— 缺失页码参数,HTTP请求必然失败(返回404或空响应),后续 ioutil.WriteFile 也因 bytes 为空或 resp.Body 已关闭而静默失效。
✅ 正确做法是使用标准库 strconv 包进行数值到字符串的安全转换:
import "strconv" // 推荐:简洁直观 adrr := "http://torhit.com/torbite/?page=" + strconv.Itoa(count) // 或更通用(适用于int64等) adrr := "http://torhit.com/torbite/?page=" + strconv.FormatInt(int64(count), 10)
此外,原代码存在多个关键缺陷,需一并修复:
立即学习“go语言免费学习笔记(深入)”;
? 必须修正的并发与资源问题
- 主协程提前退出:main() 启动200个goroutine后立即结束,所有子goroutine被强制终止。需使用 sync.WaitGroup 等待完成。
- HTTP响应体未检查错误:http.Get 和 ioutil.ReadAll 的错误被忽略(_),导致失败无提示。
- 文件权限不安全:0777 在Linux/macOS下赋予全局可执行权限,应改为 0644(仅读写)。
- 已废弃API:ioutil 在Go 1.16+已弃用,推荐使用 io.ReadAll 和 os.WriteFile。
✅ 修复后的完整可运行示例
package main
import (
"io"
"net/http"
"os"
"strconv"
"sync"
)
func excuter(count int, wg *sync.WaitGroup) {
defer wg.Done() // 标记goroutine完成
url := "http://torhit.com/torbite/?page=" + strconv.Itoa(count)
resp, err := http.Get(url)
if err != nil {
println("HTTP GET failed for page", count, ":", err.Error())
return
}
defer resp.Body.Close() // 确保Body关闭
bytes, err := io.ReadAll(resp.Body)
if err != nil {
println("Read body failed for page", count, ":", err.Error())
return
}
filename := "scrap.txt" + strconv.Itoa(count)
err = os.WriteFile(filename, bytes, 0644)
if err != nil {
println("Write file failed for", filename, ":", err.Error())
}
}
func main() {
const maxCount = 200
var wg sync.WaitGroup
for count := 1; count <= maxCount; count++ {
wg.Add(1)
go excuter(count, &wg)
}
wg.Wait() // 阻塞等待所有goroutine完成
println("Scraping completed.")
}⚠️ 注意事项
- 目标网站合规性:torhit.com 属于Tor相关站点,访问可能受网络策略限制,请确保遵守Robots协议及当地法律法规。
- 并发控制:200个并发请求易触发服务端限流或IP封禁,建议添加 time.Sleep 或使用带缓冲的goroutine池(如 semaphore)。
- 错误处理强化:生产环境应记录详细日志(如 log.Printf)、重试机制及超时设置(http.Client.Timeout)。
- 依赖更新:若使用旧版Go(<1.16),仍可用 ioutil;新版请优先采用 io/os 包。
掌握 strconv.Itoa() 是Go基础开发的关键一环——它不仅是语法纠错,更是理解类型系统与标准库设计哲学的起点。


















