zoukankan      html  css  js  c++  java
  • go实现爬虫

    条件:
    1.第三方包github.com/tebeka/selenium,selenium自动化测试工具
    2.google驱动chromedriver.exe,要与本地浏览器的版本号对应,下载:http://npm.taobao.org/mirrors/chromedriver/
    流程:
    1.开启google驱动服务
    2.设置浏览器参数
    3.开启浏览器窗口,每次调用wd,_ :=selenium.NewRemote函数都会开启一个窗口。
    3.1.比如调用页面中的某个组件,wd.FindElements(selenium.ByCSSSelector, ".xxx"),选择器符合W3C规范即可。
    4.关闭窗口,webDriver.Quit()
    5.关闭驱动服务,crawler.Service.Stop()
    代码
    type Crawler struct {
        ChromeDriver string
        Port         int
        Service      *selenium.Service
        Caps selenium.Capabilities
    }
    
    //开启驱动服务
    func NewCrawler() (*Crawler,error) {
        crawler := &Crawler{
            ChromeDriver: `E:/go_workspace/src/my_common_utils/chromedriver.exe`,//google浏览器驱动
            Port:         9515,
            Service:      nil,
        }
        opts := []selenium.ServiceOption{}
        service, err := selenium.NewChromeDriverService(crawler.ChromeDriver, crawler.Port, opts...)
        if nil != err {
            return nil,errors.New("start a chromedriver service falid,"+err.Error())
        }
        caps := selenium.Capabilities{
            "browserName": "chrome",
        }
        imagCaps := map[string]interface{}{
            "profile.managed_default_content_settings.images": 2,//不加载图片,提高浏览器响应速度
        }
        chromeCaps := chrome.Capabilities{
            Prefs: imagCaps,
            Path:  "",
            Args: []string{
                //"--headless", //不弹出窗口
                "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", // 模拟user-agent,防反爬
            },
        }
        //以上是设置浏览器参数
        caps.AddChrome(chromeCaps)
        crawler.Service = service
        crawler.Caps = caps
        return crawler,nil
    }
    
    //打开窗口
    func (c *Crawler) NewRemote()(selenium.WebDriver,error){
        w_b1, err := selenium.NewRemote(c.Caps, fmt.Sprintf("http://localhost:%d/wd/hub", c.Port))
        if err != nil {
            return nil,errors.New("connect to the webDriver faild,"+err.Error())
        }
        return w_b1,nil
    }
    
    //关闭驱动服务
    func (c *Crawler) Shutdown(){
        _ = c.Service.Stop()
    }
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    年轻人如何创业?有什么好的建议?
    青年创新创业大赛北京赛区总决赛举行
    90后瘫痪女孩靠创业改变人生
    怎么利用淘宝赚钱?具体方法有哪些?
    淘宝赚钱的方法有哪些?做淘宝要注意哪些?
    现在做淘宝赚钱吗?要注意哪些?
    2019年开淘宝店赚钱吗?需要注意什么?
    淘宝赚钱软件有哪些?具体怎么赚钱?
  • 原文地址:https://www.cnblogs.com/asceticmonks/p/13255975.html
Copyright © 2011-2022 走看看