如何获得当前页面的URL(附代码示例)

847 阅读1分钟

上一篇文章中,我们开发了一个简单的应用程序,并使用chromedp打开了google.com。在这篇文章中,我们要看一下chromedp处理页面和URL的功能之一。

开发者决定使用的方式是Golang开发者中非常流行的方式,即向函数传递一个变量的引用。我在go库中经常看到同样的模式,例如,GORM也使用同样的模式。

在今天的场景中,我们想打开chromedp的Github页面,并转到资源库中的一个文件,然后打印该页面的URL。简单而容易!所以让我们开始吧!!

为了这个目的,我们需要选择我们想要的元素来点击它。记住,我们只是想让我们手动做的事情自动进行。这意味着如果我们想打开名为util_test.go的文件,首先,我们需要进入URL:

// our selector to find the file inside the page.
selector := "a[title='util_test.go']"
tasks := chromedp.Tasks{
  // go to the page
    chromedp.Navigate("https://github.com/chromedp/chromedp"),
  // wait until the elemnt is visible and available inside the page
    chromedp.WaitEnabled(selector),
  // do a click on it
    chromedp.Click(selector),
}

所以我们已经进入了我们想要的页面,剩下的唯一步骤就是获得页面的URL。为此,我们定义了一个字符串变量,并将其传递给chromedp的Location函数:

var u string
...
chromedp.Location(&u),

下面是完整的代码:

package main

import (
    "context"
    "fmt"

    "github.com/chromedp/chromedp"
)

func main() {
    var u string
    opts := append(
        // select all the elements after the third element
        chromedp.DefaultExecAllocatorOptions[3:],
        chromedp.NoFirstRun,
        chromedp.NoDefaultBrowserCheck,
    )
    // create chromedp's context
    parentCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()

    selector := "a[title='util_test.go']"
    tasks := chromedp.Tasks{
        chromedp.Navigate("https://github.com/chromedp/chromedp"),
        chromedp.WaitEnabled(selector),
        chromedp.Click(selector),
        chromedp.Location(&u),
    }
    ctx, cancel := chromedp.NewContext(parentCtx)
    defer cancel()
    if err := chromedp.Run(ctx, tasks); err != nil {
        panic(err)
    }
    fmt.Printf("URL => %s\n", u)
}

输出是:

URL => https://github.com/chromedp/chromedp/blob/master/util_test.go