之前写的关于chromedp的文章被别人转到CSDN,很受鼓励,再来一篇golang爬虫实例
示例说明:用chromedp操作chrome,导航到baidu,然后输入“美女”,然后再翻2页,在此过程中保存cookie和所有img标签内容,并保存第一页的baidu logo为png
注释已经比较详细了,上代码:
package main import (
"bufio"
"context"
"fmt" "io/ioutil"
"log"
"os" "github.com/chromedp/cdproto/page" "time" "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/chromedp"
) var res string // 定义全局变量,用来保存爬虫的数据,注释掉了
var nodes []*cdp.Node // 定义全局变量,用来保存爬虫的数据node
var buf []byte //定义全局变量,用来保存Screenshot func main() {
var err error
// create context
ctxt, cancel := context.WithCancel(context.Background())
defer cancel() // create chrome instance
c, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf))
if err != nil {
log.Fatal(err)
} // run task list
wd, _ := os.Getwd()
err = c.Run(ctxt, chromedp.Tasks{
page.SetDownloadBehavior(page.SetDownloadBehaviorBehaviorAllow).WithDownloadPath(wd),
chromedp.Navigate(`https://www.baidu.com/`), // 访问掉队的BAT
chromedp.WaitVisible(`#kw`, chromedp.ByQuery), // 等待id=kw渲染成功,成功则说明已经获取到了正确的页面
chromedp.SendKeys(`#kw`, `美女`, chromedp.ByID), //输入关键词
chromedp.Click("#su", chromedp.ByID), // 触发点击事件,
chromedp.Sleep( * time.Second), //缓一缓
//chromedp.OuterHTML("html", &res, chromedp.ByQuery), //获取html源码
chromedp.Nodes("img", &nodes, chromedp.ByQueryAll), //获取当前页的img标签
chromedp.Screenshot("#result_logo", &buf, chromedp.ByID),
// 获取cookie
chromedp.ActionFunc(func(ctx context.Context, h cdp.Executor) error {
cookies, err := network.GetAllCookies().Do(ctx, h)
// 将cookie拼接成header请求中cookie字段的模式
var coo string
for _, v := range cookies {
coo = coo + v.Name + "=" + v.Value + ";"
}
WirteTXT(coo) //保存cookie到文件
WirteTXT(fmt.Sprintf("\r\n\r\n%s", nodes)) //保存img标签
ioutil.WriteFile("contact-form.png", buf, )
if err != nil {
return err
}
return nil
}),
chromedp.ActionFunc(func(ctx context.Context, h cdp.Executor) error {
// 循环翻页
for i := ; i < ; i++ {
//执行
err = c.Run(ctxt, chromedp.Tasks{
chromedp.Click(`#page a:nth-last-child()`, chromedp.ByID), //翻页
chromedp.Sleep( * time.Second), //缓一缓
chromedp.Nodes("img", &nodes, chromedp.ByQueryAll), //获取标签的html }) //执行爬虫任务
WirteTXT(fmt.Sprintf("\r\n\r\n%s", nodes)) //保存img标签
}
return nil
}),
})
if err != nil {
log.Fatal(err)
} } func WirteTXT(txt string) {
f, err := os.OpenFile("1.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, )
if err != nil {
fmt.Println("os Create error: ", err)
return
}
defer f.Close() bw := bufio.NewWriter(f)
bw.WriteString(txt + "\n")
bw.Flush()
}
参考:
https://godoc.org/github.com/chromedp/chromedp#Selector.Do
https://www.jianshu.com/p/d282b4a57596
https://juejin.im/entry/5aac8374518825556a722de3
https://blog.csdn.net/yang731227/article/details/89202458
https://www.cnblogs.com/midnight/p/10384627.html
https://www.cnblogs.com/midnight/p/10384699.html
https://crieit.net/posts/chromedp-Node-HTML
https://qiita.com/yoheimuta/items/bbbe84d2a7fe673720b3
https://segmentfault.com/a/1190000019705499?utm_source=tag-newest
https://stackoverflow.com/search?q=chromedp
https://cloud.tencent.com/developer/ask/173850
https://www.ribice.ba/golang-chrome-automation/
https://gitee.com/-/ide/project/kwff/chromedp/edit/master/-/errors.go
https://www.cnblogs.com/apocelipes/archive/2018/07/04/9264673.html
如果在windows安装chromedp,还可参考我之前写的
https://www.cnblogs.com/pu369/p/10315988.html
https://www.cnblogs.com/pu369/p/10345483.html
之前写的关于chromedp的文章被别人转到CSDN,很受鼓励,再来一篇golang爬虫实例的更多相关文章
- python3.4学习笔记(十三) 网络爬虫实例代码,使用pyspider抓取多牛投资吧里面的文章信息,抓取政府网新闻内容
python3.4学习笔记(十三) 网络爬虫实例代码,使用pyspider抓取多牛投资吧里面的文章信息PySpider:一个国人编写的强大的网络爬虫系统并带有强大的WebUI,采用Python语言编写 ...
- 程序员为什么要写if else,为什么要和别人不一样
程序员为什么要写if else,为什么要和别人不一样 前言 无聊,睡不着!本文只是随便写写而已!感叹一下程序员的生活! 刚看到一个八级程序员的分级,所以就写了这个随笔,分级如下: 第八级 ...
- 写的非常好的文章 C#中的委托,匿名方法和Lambda表达式
简介 在.NET中,委托,匿名方法和Lambda表达式很容易发生混淆.我想下面的代码能证实这点.下面哪一个First会被编译?哪一个会返回我们需要的结果?即Customer.ID=5.答案是6个Fir ...
- 我写的Java相关的文章
此文正在更新中... Activiti 升级到Activiti7了. Web service/Soap Java如何调用.net写的asmx服务
- 写给小白的 Nginx 文章
原文地址:Nginx concepts I wish I knew years ago 原文作者:Aemie Jariwala(已授权) 译者 & 校正:HelloGitHub-小鱼干 &am ...
- 用Unity做的一个小游戏,仿照一个样例写的,个人认为文章写的不错,哈哈
- 我写的.net相关的文章
此文正在更新中... 广州.net俱乐部相关 复活广州.net俱乐部 office365的开发者训练营,免费,在微软广州举办 被低估的.net(上) - 微软MonkeyFest 2018广州分享会活 ...
- 我写的Angular相关的文章
此文正在更新中... Angular6的变化 Angular7的变化 No value accessor for form control with path的解决方案
- Nginx 相关介绍(Nginx是什么?能干嘛?个人觉得写得比较好的文章,转载过来)
Nginx的产生 没有听过Nginx?那么一定听过它的"同行"Apache吧!Nginx同Apache一样都是一种WEB服务器.基于REST架构风格,以统一资源描述符(Unifor ...
随机推荐
- RocketMQ源码学习--消息存储篇
转载. https://blog.csdn.net/mr253727942/article/details/55805876 1.序言 今天来和大家探讨一下RocketMQ在消息存储方面所作出的努力, ...
- 三种SpringSecurity方法级别权限控制
一 JSR-250注解 1.在pom.xml添加 <dependency> <groupId>javax.annotation</groupId> <arti ...
- Web应用中访问WEB-INF下的资源
WEB-INF目录是出于保护资源文件的目的,只能我们开发人员自己查看不可以通过URL直接访问的: 有时候我们也想直接访问WEB-INF中的资源,那就需要用到请求转发了(重定向redirect是不可以的 ...
- nginx访问量统计 日常分析
nginx访问量统计 0.查询某个时间段的日志 cat appapi.dayutang.cn.access.log |grep 'POST'|grep '2019:10' > 20191059. ...
- 【Trie】The XOR-longest Path
[题目链接]: https://loj.ac/problem/10056 [题意] 请输出树上两个点的异或路径 的最大值. [题解] 这个题目,y总说过怎么做之后,简直就是醍醐灌顶了. 我们知道Xo ...
- StorageClass-动态PVC
StorageClass 之前我们部署了PV 和 PVC 的使用方法,但是前面的 PV 都是静态的,什么意思?就是我要使用的一个 PVC 的话就必须手动去创建一个 PV,我们也说过这种方式在很大程度上 ...
- Microsoft SQL Server 2008 R2 Express and Management Studio Express
https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads Microsoft SQL Server 2008 R2 RTM - E ...
- 通过ADB调试安卓程序
ADB,即 Android Debug Bridge,它是Android开发/测试人员不可替代的强大工具. 1.下载ADB后,将以下四个文件放到某个文件夹下即可.因为打开Cmd默认路径是 C:\Use ...
- springboot内置tomcat配置虚拟路径
在Springboot中默认的静态资源路径有:classpath:/METAINF/resources/,classpath:/resources/,classpath:/static/,classp ...
- System performance tools
System performance tools ============ End