如何使用Golang Colly库实现亚马逊买家账户登录以获取物流追踪信息
解决亚马逊两步式登录的Colly爬虫实现问题
你说得没错,亚马逊的登录是两步式流程,和WordPress的单页提交逻辑完全不同——直接向最终登录链接Post账号密码的方式,会跳过邮箱验证的中间步骤,自然无法完成登录。下面我会帮你调整代码,模拟真实用户的登录流程:
核心思路
- 第一步:访问邮箱输入页,提取表单中的隐藏参数(比如
openid.assoc_handle、openid.return_to等亚马逊登录必需的字段),提交邮箱后进入密码输入页。 - 第二步:在密码输入页,同样提取页面中的登录相关参数,结合邮箱和密码完成最终登录请求。
- 反爬注意:设置真实的User-Agent,保持会话Cookie的连续性,避免被亚马逊拦截。
修改后的完整代码
package main import ( "fmt" "log" "strings" "github.com/gocolly/colly" ) func main() { // 创建Collector,设置User-Agent模拟真实浏览器 c := colly.NewCollector( colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"), ) // 存储邮箱和密码(替换成你的真实账号) email := "mail@example.com" password := "123qwerty" // 第一步:处理邮箱输入页,提交邮箱 c.OnHTML("#ap_email_form", func(e *colly.HTMLElement) { // 提取表单中的所有隐藏字段 formData := make(map[string]string) e.ForEach("input[type='hidden']", func(_ int, el *colly.HTMLElement) { formData[el.Attr("name")] = el.Attr("value") }) // 添加邮箱参数 formData["email"] = email formData["continue"] = e.Attr("action") // 提交邮箱表单,进入密码页 err := e.Request.Post(e.Attr("action"), formData) if err != nil { log.Fatal("提交邮箱失败:", err) } }) // 第二步:处理密码输入页,提交密码 c.OnHTML("#ap_password_form", func(e *colly.HTMLElement) { // 提取表单中的所有隐藏字段 formData := make(map[string]string) e.ForEach("input[type='hidden']", func(_ int, el *colly.HTMLElement) { formData[el.Attr("name")] = el.Attr("value") }) // 添加邮箱和密码参数 formData["email"] = email formData["password"] = password formData["continue"] = e.Attr("action") // 提交密码表单,完成登录 err := e.Request.Post(e.Attr("action"), formData) if err != nil { log.Fatal("提交密码失败:", err) } }) // 登录成功后,访问订单历史页并打印内容 c.OnHTML(".order-history-container", func(e *colly.HTMLElement) { fmt.Println("登录成功!订单历史内容:") fmt.Println(strings.TrimSpace(e.Text)) }) // 监听响应状态,排查问题 c.OnResponse(func(r *colly.Response) { log.Printf("收到响应,状态码:%d", r.StatusCode) }) // 开始访问亚马逊登录页 loginURL := "https://www.amazon.de/-/en/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.de%2F%3Flanguage%3Den_GB%26ref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=deflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&" err := c.Visit(loginURL) if err != nil { log.Fatal("访问登录页失败:", err) } }
关键说明
- 表单参数提取:亚马逊的登录表单包含多个隐藏字段,这些字段是验证会话合法性的关键,必须随账号密码一起提交,不能省略。
- 会话保持:Colly的Collector会自动管理Cookie,所以只要在同一个Collector实例中完成所有步骤,就能保持登录状态。
- 反爬应对:如果还是遇到拦截,可以尝试添加随机延迟(
colly.Async(true)配合time.Sleep),或者使用代理IP,但请注意亚马逊的反爬规则,避免触发账号风控。
内容的提问来源于stack exchange,提问作者Melisa
相关产品推荐
相关产品推荐

