chromedp+goquery爬取打字邀请码实战

背景:

最近一直在研究钉钉机器人用于推送消息,突然想到小组同学经常会键盘打字竞赛,竞赛所用的邀请码一直是手动获取,不够自动化,较为繁琐,想着给钉钉机器人添加一个定时推送打字邀请码的功能,方便大家打字,提高效率。

思路分析

最近了解了Golang的chromedp库,此库功能十分强大,能够让电脑自动操控浏览器,不需要人为介入。而且还能截图,这就解决了二维码登录的难题。爬虫的话,使用的是goquery(貌似chromedp也能爬虫)。

实现过程

package main

import (
	"context"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/chromedp/chromedp"
	"log"
	"strings"
	"time"
)

func main() {
	opts := append(
		chromedp.DefaultExecAllocatorOptions[:],
		chromedp.NoDefaultBrowserCheck, //不检查默认浏览器
		chromedp.Flag("headless", false),// 禁用chrome headless(禁用无窗口模式,那就是开启窗口模式)
		chromedp.Flag("blink-settings", "imagesEnabled=true"), //开启图像界面,重点是开启这个
		chromedp.Flag("ignore-certificate-errors", true),      //忽略错误
		chromedp.Flag("disable-web-security", true),           //禁用网络安全标志
		chromedp.Flag("disable-extensions", true),             //开启插件支持
		chromedp.Flag("disable-default-apps", true),
		chromedp.NoFirstRun, //设置网站不是首次运行
		chromedp.WindowSize(1921, 1024),
		chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"), //设置UserAgent
	)
	allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	//defer cancel()
	print(cancel)

	// 创建上下文实例
	ctx, cancel := chromedp.NewContext(
		allocCtx,
		chromedp.WithLogf(log.Printf),
	)
	//defer cancel()

	// 创建超时上下文
	var b *string
	var TypingInvitationCode string
	var html string
	ctx, cancel = context.WithTimeout(ctx, 10*time.Minute)

	err := chromedp.Run(ctx,
		chromedp.Navigate("https://dazi.kukuw.com/"),

		//点击“我的打字“按钮
		chromedp.Click(`document.getElementById("globallink").getElementsByTagName("a")[5]`, chromedp.ByJSPath),
		// 锁定用户名框并填写内容
		chromedp.WaitVisible(`document.querySelector("#name")`,chromedp.ByJSPath),
		chromedp.SetValue(`document.querySelector("#name")`, "name", chromedp.ByJSPath),
		//锁定密码框并填写内容
		chromedp.WaitVisible(`document.querySelector("#pass")`,chromedp.ByJSPath),
		chromedp.SetValue(`document.querySelector("#pass")`, "password", chromedp.ByJSPath),
		//点击登录按钮
		chromedp.WaitVisible(`document.querySelector(".button").firstElementChild`, chromedp.ByJSPath),
		chromedp.Click(`document.querySelector(".button").firstElementChild`, chromedp.ByJSPath),
		//点击发布竞赛
		chromedp.WaitVisible(`document.querySelector("a.groupnew")`, chromedp.ByJSPath),
		chromedp.Click(`document.querySelector("a.groupnew")`, chromedp.ByJSPath),
		chromedp.Sleep(time.Second),
		点击所要打字的文章
		chromedp.WaitVisible(`document.querySelector("a#select_b.select_b")`, chromedp.ByJSPath),
		chromedp.Click(`document.querySelector("a#select_b.select_b")`,chromedp.ByJSPath),
		chromedp.WaitVisible(`document.querySelector("a.sys.on")`, chromedp.ByJSPath),
		chromedp.Click(`document.querySelector("a.sys.on")`,chromedp.ByJSPath),
		//选择有效期
		chromedp.Evaluate("document.querySelector(\"select#youxiaoqi\").value = document.querySelector(\"select#youxiaoqi\").children[5].value",nil),
		//设置成为不公开
		chromedp.Click(`document.querySelectorAll("input#gongkai")[1]`,chromedp.ByJSPath),
		//点击发布按钮
		chromedp.Click(`document.querySelectorAll(".artnew table tr td input")[7]`,chromedp.ByJSPath),
		chromedp.WaitVisible(`document.querySelectorAll("#my_main .art_table td")[9].childNodes[0]`,chromedp.ByJSPath),
		chromedp.ActionFunc(func(ctx context.Context) error {
			fmt.Println("打字吗出现了")
			return nil
		}),
		chromedp.ActionFunc(func(ctx context.Context) error {
			fmt.Println("爬取前:",TypingInvitationCode)
			a := chromedp.OuterHTML(`document.querySelector("body")`, &html, chromedp.ByJSPath)
			a.Do(ctx)
			fmt.Println("888888888888",html)
			dom, err := goquery.NewDocumentFromReader(strings.NewReader(html))
			if err != nil {
				fmt.Println("123", err.Error())
				return err
			}
			dom.Find(`#my_main > .art_table > tbody > tr:nth-child(2)`).Each(func(i int, selection *goquery.Selection) {
				TypingInvitationCode = TypingInvitationCode + selection.Text()
				selection.Next()
			})
			fmt.Println("爬取后:",TypingInvitationCode)
			return err
		}),

	)
	time.Sleep(10*time.Second)
	fmt.Println(b)
	if err != nil {

	}
}

关键函数讲解

一:Flag函数

chromedp.Flag("headless", false),// 禁用chrome headless(禁用无窗口模式,那就是开启窗口模式)

该函数可以的chromedp进行一些配置,其中headless英文意思是无窗口的,后面第二个参数是fasle,说明禁用掉了无窗口,那就是运行程序的时候,有对应的窗口运行出来。

二:Click函数

chromedp.Click(`document.getElementById("globallink").getElementsByTagName("a")[5]`, chromedp.ByJSPath)

该函数是模拟鼠标点击,第一个参数 sel interface 是用来确定页面元素的筛选规则,第二个参数 opts ...QueryOption是描述第一个参数的,用来说明第一个参数的语法。我们上面的document.getElementById("globallink").getElementsByTagName("a")[5] 就是JavaScript的DOM操作,所以第二个参数是 chromedp.ByJSPath。

三:WaitVisible函数

chromedp.WaitVisible(`document.querySelector("#name")`,chromedp.ByJSPath),

其用法是和Click函数相似,功能是等待页面中的某一元素出现,才继续往下执行,如果页面中某个按钮还没出现,我们就使用了Click功能,此处就会出现错误(代码中无法体现,也不报错,但是代码不再生效)。

四:SetValue函数

chromedp.SetValue(`document.querySelector("#pass")`, "123456", chromedp.ByJSPath)

该函数是在文本框中输入值,第一个参数确定到文本框,第二个参数是要设置的,第三个参数是描述第一个参数的,和前面的同理。

五 :Evaluate函数

hromedp.Evaluate("document.querySelector(\"select#youxiaoqi\").value = document.querySelector(\"select#youxiaoqi\").children[5].value",nil),

该函数是在页面上面执行JavaScript代码,第一个参数是要执行的代码,第二个参数和第三个参数暂时没用过,此处省略。 使用该函数是为了解决Click无法点击复选框Select中的选项Option,所以转化思路只把设置Select的Value元素。

六:ActionFunc 函数

chromedp.ActionFunc(func(ctx context.Context) error {
			fmt.Println("爬取前:",TypingInvitationCode)
			a := chromedp.OuterHTML(`document.querySelector("body")`, &html, chromedp.ByJSPath)
			a.Do(ctx) //chromedp把整个页面的元素都爬下来放在html中
			fmt.Println("888888888888",html)
			dom, err := goquery.NewDocumentFromReader(strings.NewReader(html))
			if err != nil {
				fmt.Println("123", err.Error())
				return err
			}
            //使用goquery筛选元素,Find函数中的参数就是筛选规则,具体规则是前端内容,可以参考博客:https://blog.csdn.net/qq_24393347/article/details/100293833
            //Find函数筛选出来的是一个数组元素,我们可以使用Each和Next函数遍历,从而取到单个
			dom.Find(`#my_main > .art_table > tbody > tr:nth-child(2) > td:nth-child(4) > span`).Each(func(i int, selection *goquery.Selection) {
				TypingInvitationCode = TypingInvitationCode + selection.Text()
				selection.Next()
			})
            //我们也可以使用下面的方式获取单个元素
            TypingInvitationCode = dom.Find(`#my_main > .art_table > tbody > tr:nth-child(2) > td:nth-child(4) > span`).First().Text()
            
			fmt.Println("爬取后:",TypingInvitationCode)
			return err
		}),

chromepy支持自定义函数,我们可以在自定义函数中写其他我们需要的代码,上面代码就在自定义函数中使用了goquery爬取最终的数据。

注意事项

上面的代码想要写的一个bug都没有,也是不容易的,短短的不到100行的代码耗费了整整一天时间,有一些比较细的,容易采坑的点,给大家记录一下。

注意一:chromeqp.Run函数调试不便

err := chromedp.Run(ctx,
		chromedp.Navigate("https://dazi.kukuw.com/"),

		//点击“我的打字“按钮
		chromedp.Click(`document.getElementById("globallink").getElementsByTagName("a")[5]`, chromedp.ByJSPath),
		// 锁定用户名框并填写内容
		chromedp.WaitVisible(`document.querySelector("#name")`,chromedp.ByJSPath),
        ....
)

Run函数中的代码是一下全部加载一遍,然后最后再执行Run函数,我们无法看到代码一步一步的执行,再加上没有error返回,所以有了错误也没办法查看。其实也可以调试,那就是进入源码打上断电,看源码一步一步走,但是还是没有办法直接看到错误返回。而且还没有办法直接打印,所以没法调试。

所以,最直接的还是每一步都设置一下WaitVisible 并且一定要把 sel 筛选规则写对,如何查看筛选规则是否正确可以直接打开网页的调试工具,找到控制台,输入即可,比如说,我们想要找到不公开的按钮。 

 注意二:复选框Select中的Option选项无法被点击

 如果我想点击选择12小时,模式点击无法实现,具体原因不详,反正锁定到元素之后,点击就是不生效,后面发现Evaluate函数可以直接在网页上面执行Js脚本文件,所以执行脚本文件,将Select中的Value改掉即可

默认选中的是半小时,Value是30,我们直接改成720即可实现选中12小时,具体js代码再上方代码中。

注意点三 : goquery中的筛选规则 :nth-child(n)

 这个 : 的左边和右边是不能有空格的,如果有空格,不生效。

最终成品效果如下:

20220929_155859

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值