How to use Matches method of rod Package

Best Rod code snippet using rod.Matches

main.go

Source:main.go Github

copy

Full Screen

...120}121func (c *Context) getCompetitionGames(url string) []string {122 page := c.Browser.MustPage(url)123 defer page.Close()124 allMatches := []string{}125 content := page.MustElement(".content-column")126 if content.MustHas(".block_competition_matches_full") {127 fmt.Println("Assuming cup competition")128 blocks := content.MustElements(".block_competition_matches_full")129 for _, block := range blocks {130 matches := block.MustElement("tbody").MustElements(".match")131 for _, match := range matches {132 m := match.MustElement(".score-time").MustElement("a").MustAttribute("href")133 if m == nil {134 continue135 }136 allMatches = append(allMatches, urlPrefix+*m)137 }138 }139 return allMatches140 }141 block := content.MustElement(".block_competition_matches_summary")142 if block.MustHas("select") {143 fmt.Println("Assuming league with game weeks")144 selector := block.MustElement("select")145 for _, val := range selector.MustElements("option") {146 selector.MustSelect(val.MustText())147 time.Sleep(1000 * time.Millisecond)148 block = content.MustElement(".block_competition_matches_summary")149 matches := block.MustElement("tbody").MustElements(".match")150 for _, match := range matches {151 m := match.MustElement(".score-time").MustElement("a").MustAttribute("href")152 if m == nil {153 continue154 }155 allMatches = append(allMatches, urlPrefix+*m)156 }157 }158 return allMatches159 }160 fmt.Println("Assuming disorganized league")161 matchMap := map[string]interface{}{}162 time.Sleep(1000 * time.Millisecond)163 // Click on agree cookies164 if page.MustHas(".qc-cmp2-summary-buttons") {165 el := page.MustElement(".qc-cmp2-summary-buttons")166 el.MustElements("button")[1].MustClick()167 }168 for block.MustHas(".previous:not(.disabled)") {169 matches := block.MustElement("tbody").MustElements(".match")170 for _, match := range matches {171 m := match.MustElement(".score-time").MustElement("a").MustAttribute("href")172 if m == nil {173 continue174 }175 matchMap[urlPrefix+*m] = nil176 }177 previous := block.MustElement(".previous")178 previous.MustClick()179 time.Sleep(1000 * time.Millisecond)180 block = content.MustElement(".block_competition_matches_summary")181 }182 matches := block.MustElement("tbody").MustElements(".match")183 for _, match := range matches {184 m := match.MustElement(".score-time").MustElement("a").MustAttribute("href")185 if m == nil {186 continue187 }188 matchMap[urlPrefix+*m] = nil189 }190 for url, _ := range matchMap {191 allMatches = append(allMatches, url)192 }193 return allMatches194}195func (c *Context) updateWithGame(page *rod.Page, url string) error {196 content := page.MustElement(".content-column")197 lineupsElems := content.MustElements(".combined-lineups-container")198 if len(lineupsElems) != 2 {199 return errors.New("$$$$$***** INVESTIGATE *****$$$$$ " + url)200 }201 allGoals := []db.Goal{}202 allSubs := []db.Substitution{}203 totalTime := 90204 home, goals, subs, totime, err := parseLuElem(lineupsElems[0], true)205 if err != nil {206 return err207 }...

Full Screen

Full Screen

utils.go

Source:utils.go Github

copy

Full Screen

1package rod2import (3 "bytes"4 "context"5 "encoding/base64"6 "encoding/json"7 "fmt"8 "io"9 "log"10 "net/http"11 "os"12 "path/filepath"13 "reflect"14 "regexp"15 "runtime/debug"16 "sync"17 "time"18 "github.com/go-rod/rod/lib/cdp"19 "github.com/go-rod/rod/lib/proto"20 "github.com/go-rod/rod/lib/utils"21)22// CDPClient is usually used to make rod side-effect free. Such as proxy all IO of rod.23type CDPClient interface {24 Event() <-chan *cdp.Event25 Call(ctx context.Context, sessionID, method string, params interface{}) ([]byte, error)26}27// Message represents a cdp.Event28type Message struct {29 SessionID proto.TargetSessionID30 Method string31 lock *sync.Mutex32 data json.RawMessage33 event reflect.Value34}35// Load data into e, returns true if e matches the event type.36func (msg *Message) Load(e proto.Event) bool {37 if msg.Method != e.ProtoEvent() {38 return false39 }40 eVal := reflect.ValueOf(e)41 if eVal.Kind() != reflect.Ptr {42 return true43 }44 eVal = reflect.Indirect(eVal)45 msg.lock.Lock()46 defer msg.lock.Unlock()47 if msg.data == nil {48 eVal.Set(msg.event)49 return true50 }51 utils.E(json.Unmarshal(msg.data, e))52 msg.event = eVal53 msg.data = nil54 return true55}56// DefaultLogger for rod57var DefaultLogger = log.New(os.Stdout, "[rod] ", log.LstdFlags)58// DefaultSleeper generates the default sleeper for retry, it uses backoff to grow the interval.59// The growth looks like:60//61// A(0) = 100ms, A(n) = A(n-1) * random[1.9, 2.1), A(n) < 1s62//63// Why the default is not RequestAnimationFrame or DOM change events is because of if a retry never64// ends it can easily flood the program. But you can always easily config it into what you want.65var DefaultSleeper = func() utils.Sleeper {66 return utils.BackoffSleeper(100*time.Millisecond, time.Second, nil)67}68// PagePool to thread-safely limit the number of pages at the same time.69// It's a common practice to use a channel to limit concurrency, it's not special for rod.70// This helper is more like an example to use Go Channel.71// Reference: https://golang.org/doc/effective_go#channels72type PagePool chan *Page73// NewPagePool instance74func NewPagePool(limit int) PagePool {75 pp := make(chan *Page, limit)76 for i := 0; i < limit; i++ {77 pp <- nil78 }79 return pp80}81// Get a page from the pool. Use the PagePool.Put to make it reusable later.82func (pp PagePool) Get(create func() *Page) *Page {83 p := <-pp84 if p == nil {85 p = create()86 }87 return p88}89// Put a page back to the pool90func (pp PagePool) Put(p *Page) {91 pp <- p92}93// Cleanup helper94func (pp PagePool) Cleanup(iteratee func(*Page)) {95 for i := 0; i < cap(pp); i++ {96 p := <-pp97 if p != nil {98 iteratee(p)99 }100 }101}102// BrowserPool to thread-safely limit the number of browsers at the same time.103// It's a common practice to use a channel to limit concurrency, it's not special for rod.104// This helper is more like an example to use Go Channel.105// Reference: https://golang.org/doc/effective_go#channels106type BrowserPool chan *Browser107// NewBrowserPool instance108func NewBrowserPool(limit int) BrowserPool {109 pp := make(chan *Browser, limit)110 for i := 0; i < limit; i++ {111 pp <- nil112 }113 return pp114}115// Get a browser from the pool. Use the BrowserPool.Put to make it reusable later.116func (bp BrowserPool) Get(create func() *Browser) *Browser {117 p := <-bp118 if p == nil {119 p = create()120 }121 return p122}123// Put a browser back to the pool124func (bp BrowserPool) Put(p *Browser) {125 bp <- p126}127// Cleanup helper128func (bp BrowserPool) Cleanup(iteratee func(*Browser)) {129 for i := 0; i < cap(bp); i++ {130 p := <-bp131 if p != nil {132 iteratee(p)133 }134 }135}136var _ io.ReadCloser = &StreamReader{}137// StreamReader for browser data stream138type StreamReader struct {139 Offset *int140 c proto.Client141 handle proto.IOStreamHandle142 buf *bytes.Buffer143}144// NewStreamReader instance145func NewStreamReader(c proto.Client, h proto.IOStreamHandle) *StreamReader {146 return &StreamReader{147 c: c,148 handle: h,149 buf: &bytes.Buffer{},150 }151}152func (sr *StreamReader) Read(p []byte) (n int, err error) {153 res, err := proto.IORead{154 Handle: sr.handle,155 Offset: sr.Offset,156 }.Call(sr.c)157 if err != nil {158 return 0, err159 }160 if !res.EOF {161 var bin []byte162 if res.Base64Encoded {163 bin, err = base64.StdEncoding.DecodeString(res.Data)164 if err != nil {165 return 0, err166 }167 } else {168 bin = []byte(res.Data)169 }170 _, _ = sr.buf.Write(bin)171 }172 return sr.buf.Read(p)173}174// Close the stream, discard any temporary backing storage.175func (sr *StreamReader) Close() error {176 return proto.IOClose{Handle: sr.handle}.Call(sr.c)177}178// Try try fn with recover, return the panic as rod.ErrTry179func Try(fn func()) (err error) {180 defer func() {181 if val := recover(); val != nil {182 err = &ErrTry{val, string(debug.Stack())}183 }184 }()185 fn()186 return err187}188func genRegMatcher(includes, excludes []string) func(string) bool {189 regIncludes := make([]*regexp.Regexp, len(includes))190 for i, p := range includes {191 regIncludes[i] = regexp.MustCompile(p)192 }193 regExcludes := make([]*regexp.Regexp, len(excludes))194 for i, p := range excludes {195 regExcludes[i] = regexp.MustCompile(p)196 }197 return func(s string) bool {198 for _, include := range regIncludes {199 if include.MatchString(s) {200 for _, exclude := range regExcludes {201 if exclude.MatchString(s) {202 goto end203 }204 }205 return true206 }207 }208 end:209 return false210 }211}212type saveFileType int213const (214 saveFileTypeScreenshot saveFileType = iota215 saveFileTypePDF216)217func saveFile(fileType saveFileType, bin []byte, toFile []string) error {218 if len(toFile) == 0 {219 return nil220 }221 if toFile[0] == "" {222 stamp := fmt.Sprintf("%d", time.Now().UnixNano())223 switch fileType {224 case saveFileTypeScreenshot:225 toFile = []string{"tmp", "screenshots", stamp + ".png"}226 case saveFileTypePDF:227 toFile = []string{"tmp", "pdf", stamp + ".pdf"}228 }229 }230 return utils.OutputFile(filepath.Join(toFile...), bin)231}232func httHTML(w http.ResponseWriter, body string) {233 w.Header().Add("Content-Type", "text/html; charset=utf-8")234 _, _ = w.Write([]byte(body))235}236func mustToJSONForDev(value interface{}) string {237 buf := new(bytes.Buffer)238 enc := json.NewEncoder(buf)239 enc.SetEscapeHTML(false)240 utils.E(enc.Encode(value))241 return buf.String()242}243// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs244var regDataURI = regexp.MustCompile(`\Adata:(.+?)?(;base64)?,`)245func parseDataURI(uri string) (string, []byte) {246 matches := regDataURI.FindStringSubmatch(uri)247 l := len(matches[0])248 contentType := matches[1]249 bin, _ := base64.StdEncoding.DecodeString(uri[l:])250 return contentType, bin251}...

Full Screen

Full Screen

tool.go

Source:tool.go Github

copy

Full Screen

1package xray_aio2import (3 "fmt"4 "github.com/WQGroup/logger"5 "github.com/allanpk716/xray_pool/internal/pkg/rod_helper"6 "github.com/allanpk716/xray_pool/internal/pkg/settings"7 "github.com/go-rod/rod"8 "net/http"9 "net/url"10 "regexp"11 "strings"12 "time"13)14// TestNode 获取节点代理访问外网的延迟15func (x *XrayAIO) TestNode(url string, port int, timeout int) (int, string) {16 start := time.Now()17 res, e := x.GetBySocks5Proxy(url, "127.0.0.1", port, time.Duration(timeout)*time.Second)18 elapsed := time.Since(start)19 if e != nil {20 logger.Warn(e)21 return -1, "Error"22 }23 result, status := int(float32(elapsed.Nanoseconds())/1e6), res.Status24 defer res.Body.Close()25 return result, status26}27// GetBySocks5Proxy 通过Socks5代理访问网站28func (x *XrayAIO) GetBySocks5Proxy(objUrl, proxyAddress string, proxyPort int, timeOut time.Duration) (*http.Response, error) {29 proxy := func(_ *http.Request) (*url.URL, error) {30 return url.Parse(fmt.Sprintf("socks5://%s:%d", proxyAddress, proxyPort))31 }32 transport := &http.Transport{Proxy: proxy}33 client := &http.Client{34 Transport: transport,35 Timeout: timeOut,36 }37 return client.Get(objUrl)38}39func (x *XrayAIO) TestNodeByRod(appSettings *settings.AppSettings,40 browser *rod.Browser,41 targetUrl string,42 timeout int) (int, string) {43 start := time.Now()44 page, statusCode, _, err := rod_helper.NewPageNavigate(browser,45 fmt.Sprintf("http://127.0.0.1:%d", x.OneProxySettings.HttpPort),46 targetUrl, time.Duration(timeout)*time.Second)47 if err != nil {48 return -1, "Error"49 }50 defer func() {51 if page != nil {52 _ = page.Close()53 }54 }()55 elapsed := time.Since(start)56 speedResult := int(float32(elapsed.Nanoseconds()) / 1e6)57 pageHtmlString, err := page.HTML()58 if err != nil {59 return -1, "Error"60 }61 if appSettings.TestUrlStatusCode != 0 {62 // 需要判断63 if statusCode != appSettings.TestUrlStatusCode {64 return -1, "Error statusCode"65 }66 }67 for _, word := range appSettings.TestUrlFailedWords {68 if strings.Contains(strings.ToLower(pageHtmlString), word) == true {69 return -1, "Error FailedWord " + word70 }71 }72 if appSettings.TestUrlFailedRegex != "" {73 FailedRegex := regexp.MustCompile(appSettings.TestUrlFailedRegex)74 matches := FailedRegex.FindAllString(pageHtmlString, -1)75 if matches == nil || len(matches) == 0 {76 // 没有找到匹配的内容,那么认为是成功的77 } else {78 // 匹配到了失败的内容,那么认为是失败的79 return -1, "Error FailedRegex"80 }81 }82 return speedResult, "OK"83}...

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().MustConnect()4 page := browser.MustPage("")5 input := page.MustElement("input[name=q]")6 input.MustInput("rod")7 list := page.MustElement(".erkvQe")8 suggestions := list.MustElements("li span")9 for _, s := range suggestions {10 text := s.MustText()11 fmt.Println(text)12 }13}14import (15func main() {16 browser := rod.New().MustConnect()17 page := browser.MustPage("")18 input := page.MustElement("input[name=q]")19 input.MustInput("rod")20 list := page.MustElement(".erkvQe")21 suggestions := list.MustElements("li span")22 for _, s := range suggestions {23 text := s.MustText()24 fmt.Println(text)25 }26}27import (28func main() {29 browser := rod.New().MustConnect()30 page := browser.MustPage("")31 input := page.MustElement("input[name=q]")32 input.MustInput("rod")33 list := page.MustElement(".erkvQe")34 suggestions := list.MustElements("li span")

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 regex, err := regexp.Compile(pattern)4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(regex.MatchString("12345"))8 fmt.Println(regex.MatchString("1234x"))9 fmt.Println(regex.MatchString("x1234"))10}11import (12func main() {13 regex, err := regexp.Compile(pattern)14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println(regex.FindString("12345"))18 fmt.Println(regex.FindString("1234x"))19 fmt.Println(regex.FindString("x1234"))20}21import (22func main() {23 regex, err := regexp.Compile(pattern)24 if err != nil {25 fmt.Println(err)26 }27 fmt.Println(regex.FindAllString("12345", -1))28 fmt.Println(regex.FindAllString("1234x", -1))29 fmt.Println(regex.FindAllString("x1234", -1))30}

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 re, err := regexp.Compile(pattern)4 if err != nil {5 fmt.Println("Error compiling regexp:", err)6 }7 match := re.MatchString("1234")8 fmt.Println("Match found:", match)9}10import (11func main() {12 re, err := regexp.Compile(pattern)13 if err != nil {14 fmt.Println("Error compiling regexp:", err)15 }16 result := re.FindString("1234")17 fmt.Println("Result found:", result)18}19import (20func main() {21 re, err := regexp.Compile(pattern)22 if err != nil {23 fmt.Println("Error compiling regexp:", err)24 }25 result := re.FindAllString("1234 5678 90", -1)26 fmt.Println("Result found:", result)27}28import (29func main() {30 pattern := "([0-9]+) ([0-9]+) ([0-9]+)"31 re, err := regexp.Compile(pattern

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 match, _ := regexp.MatchString("p([a-z]+)ch", "peach")4 fmt.Println(match)5 r, _ := regexp.Compile("p([a-z]+)ch")6 fmt.Println(r.MatchString("peach"))7 fmt.Println(r.FindString("peach punch"))8 fmt.Println(r.FindStringIndex("peach punch"))9 fmt.Println(r.FindStringSubmatch("peach punch"))10 fmt.Println(r.FindStringSubmatchIndex("peach punch"))11 fmt.Println(r.FindAllString("peach punch pinch", -1))12 fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))13 fmt.Println(r.FindAllString("peach punch pinch", 2))14 fmt.Println(r.Match([]byte("peach")))15 r = regexp.MustCompile("p([a-z]+)ch")16 fmt.Println(r)17 fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))18 in := []byte("a peach")19 out := r.ReplaceAllFunc(in, bytes.ToUpper)20 fmt.Println(string(out))21}22import (23func main() {24 match, _ := regexp.MatchString("p([a-z]+)ch", "peach")25 fmt.Println(match)26}27import (28func main() {29 r, _ := regexp.Compile("p([a-z]+)ch")30 fmt.Println(r)31}32import (33func main() {34 r := regexp.MustCompile("p([a-z]+)ch")35 fmt.Println(r)36}37import (38func main() {39 r := regexp.MustCompile("p([a-z]+)ch")40 fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))41}

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().MustConnect()4 defer browser.MustClose()5 page := browser.MustPage(url)6 defer page.MustClose()7 element := page.MustElement("input[name='q']")8 element.MustInput("Rod Page Object")9 button := page.MustElement("input[name='btnK']")10 button.MustClick()11 page.MustWaitLoad()12 result := page.MustElement(".g")13 text := result.MustText()14 fmt.Println(text)15}16import (17func main() {18 browser := rod.New().MustConnect()19 defer browser.MustClose()20 page := browser.MustPage(url)21 defer page.MustClose()22 element := page.MustElement("input[name='q']")23 element.MustInput("Rod Page Object")24 button := page.MustElement("input[name='btnK']")25 button.MustClick()26 page.MustWaitLoad()27 result := page.MustElement(".g")28 text := result.MustText()29 fmt.Println(text)30}31import (32func main() {33 browser := rod.New().MustConnect()34 defer browser.MustClose()

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var pattern = regexp.MustCompile(`quick\s(brown).+?(jumps)`)4 fmt.Println(pattern.MatchString(str))5 fmt.Println(pattern.FindString(str))6 fmt.Println(pattern.FindStringSubmatch(str))7 fmt.Println(pattern.FindStringIndex(str))8 fmt.Println(pattern.FindStringSubmatchIndex(str))9 fmt.Println(pattern.FindAllString(str, -1))10 fmt.Println(pattern.FindAllStringSubmatch(str, -1))11 fmt.Println(pattern.FindAllStringIndex(str, -1))12 fmt.Println(pattern.FindAllStringSubmatchIndex(str, -1))13 fmt.Println(pattern.Match([]byte(str)))14 fmt.Println(pattern.Find([]byte(str)))15 fmt.Println(pattern.FindSubmatch([]byte(str)))16 fmt.Println(pattern.FindIndex([]byte(str)))17 fmt.Println(pattern.FindSubmatchIndex([]byte(str)))18 fmt.Println(pattern.FindAll([]byte(str), -1))19 fmt.Println(pattern.FindAllSubmatch([]byte(str), -1))20 fmt.Println(pattern.FindAllIndex([]byte(str), -1))21 fmt.Println(pattern.FindAllSubmatchIndex([]byte(str), -1))22}

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r, _ := regexp.Compile("p([a-z]+)ch")4 fmt.Println(r.MatchString("peach"))5 fmt.Println(r.FindString("peach punch"))6 fmt.Println(r.FindStringIndex("peach punch"))7 fmt.Println(r.FindStringSubmatch("peach punch"))8 fmt.Println(r.FindStringSubmatchIndex("peach punch"))9 fmt.Println(r.FindAllString("peach punch pinch", -1))10 fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))11 fmt.Println(r.FindAllString("peach punch pinch", 2))12 fmt.Println(r.Match([]byte("peach")))13 r = regexp.MustCompile("p([a-z]+)ch")14 fmt.Println(r)15 fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))16 in := []byte("a peach")17 out := r.ReplaceAllFunc(in, bytes.ToUpper)18 fmt.Println(string(out))19}20import (21func main() {22 match, _ := regexp.MatchString("p([a-z]+)ch", "peach")

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 re := regexp.MustCompile("p([a-z]+)ch")4 r := regexp.MustCompile("p([a-z]+)ch")5 fmt.Println(r)6 in := []byte("a peach")

Full Screen

Full Screen

Matches

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 reg, err := regexp.Compile(pattern)4 if err != nil {5 fmt.Println("Error compiling regex:", err)6 }7 match := reg.MatchString("test")8 fmt.Println("Match:", match)9 result := reg.FindString("test")10 fmt.Println("Find:", result)11}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Rod automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful