ytsr
Minimal and fast YouTube search library for Go.
Install
go get github.com/nixietab/ytsr
Usage
package main
import (
"context"
"fmt"
"github.com/nixietab/ytsr"
)
func main() {
ctx := context.Background()
client := ytsr.New()
video, err := client.First(ctx, "never gonna give you up")
if err != nil {
panic(err)
}
fmt.Println(video.Title, video.ID, video.URL, video.Thumbnail)
videos, err := client.Search(ctx, "lofi beats", 5)
if err != nil {
panic(err)
}
for _, v := range videos {
fmt.Println(v.Title)
}
}
API
ytsr.New(opts ...Option) *Client - create a client; options: WithHTTPClient, WithUserAgent, WithLanguage, WithRegion
(*Client).Search(ctx, query string, limit int) ([]Video, error) - top results for a query
(*Client).First(ctx, query string) (Video, error) - top result only
ytsr.GetByID(id string) (Video, error) - build a Video from an ID
ytsr.ExtractVideoID(u string) (string, error) - extract an ID from a YouTube URL
Video
| Field |
Description |
ID |
YouTube video ID |
Title |
Video title |
URL |
Canonical watch?v= URL |
Thumbnail |
Largest thumbnail URL from the page |
Errors
Search failures return sentinel errors where applicable: ytsr.ErrNoResults and ytsr.ErrParse.
Note
- Scraping relies on YouTube's HTML structure (
ytInitialData) and may break if YouTube changes it.
License
GNU Affero General Public License v3.0