go get -u github.com/playwright-community/playwright-go
安装相关浏览器和操作系统依赖项:
go run github.com/playwright-community/playwright-go/cmd/playwright@latest install --with-deps
# Or
go install github.com/playwright-community/playwright-go/cmd/playwright@latest
playwright install --with-deps
packagemainimport("fmt""log""github.com/playwright-community/playwright-go")funcmain(){pw,err:=playwright.Run()iferr!=nil{log.Fatalf("could not start playwright: %v",err)}browser,err:=pw.Chromium.Launch()iferr!=nil{log.Fatalf("could not launch browser: %v",err)}page,err:=browser.NewPage()iferr!=nil{log.Fatalf("could not create page: %v",err)}if_,err=page.Goto("https://news.ycombinator.com");err!=nil{log.Fatalf("could not goto: %v",err)}entries,err:=page.Locator(".athing").All()iferr!=nil{log.Fatalf("could not get entries: %v",err)}fori,entry:=rangeentries{title,err:=entry.Locator("td.title > span > a").TextContent()iferr!=nil{log.Fatalf("could not get text content: %v",err)}fmt.Printf("%d: %s\n",i+1,title)}iferr=browser.Close();err!=nil{log.Fatalf("could not close browser: %v",err)}iferr=pw.Stop();err!=nil{log.Fatalf("could not stop Playwright: %v",err)}}
packagemainimport("encoding/xml""fmt""github.com/playwright-community/playwright-go""io""log""net/http""time")typeUrlsetstruct{XMLNamexml.Name`xml:"urlset"`Xmlnsstring`xml:"xmlns,attr"`Urls[]Url`xml:"url"`}typeUrlstruct{Locstring`xml:"loc"`Lastmodstring`xml:"lastmod"`}funcmain(){sites:=formatSiteXml("https://overstarry.vip/sitemap.xml")pw,err:=playwright.Run()iferr!=nil{log.Fatalf("could not launch playwright: %v",err)}browser,err:=pw.Chromium.Launch()iferr!=nil{log.Fatalf("could not launch Chromium: %v",err)}page,err:=browser.NewPage()iferr!=nil{log.Fatalf("could not create page: %v",err)}for_,site:=rangesites{if_,err=page.Goto(site,playwright.PageGotoOptions{WaitUntil:playwright.WaitUntilStateDomcontentloaded,});err!=nil{log.Fatalf("could not goto: %v",err)}if_,err=page.Screenshot(playwright.PageScreenshotOptions{Path:playwright.String(fmt.Sprintf("./img/%d.png",time.Now().Unix())),});err!=nil{log.Fatalf("could not create screenshot: %v",err)}}iferr=browser.Close();err!=nil{log.Fatalf("could not close browser: %v",err)}iferr=pw.Stop();err!=nil{log.Fatalf("could not stop Playwright: %v",err)}}funcformatSiteXml(sitemapURLstring)[]string{resp,err:=http.Get(sitemapURL)iferr!=nil{log.Fatal(err)}deferresp.Body.Close()bytes,err:=io.ReadAll(resp.Body)iferr!=nil{log.Fatal(err)}varurlsetUrlseterr=xml.Unmarshal(bytes,&urlset)iferr!=nil{log.Fatal(err)}urls:=make([]string,0)for_,url:=rangeurlset.Urls{urls=append(urls,url.Loc)}returnurls}