How to Scrape Twitter (X) with Go: Advanced Search Operators, Account Timelines, and a Cron Watcher (2026)
"Twitter advanced search" gets about 18,100 US searches a month, and another 1,900 people a month search for how to "search twitter without account".
Both groups want the same thing: type from:golang released min_faves:500 -filter:retweets and get a clean list of posts back, ideally in a script that can run every hour.
In 2026 that is harder than it looks. The search page needs a login, the official API bills per post returned, and none of the logged-out tricks that used to work are left.
This post builds xsearch, a small Go tool (standard library only) that does it the other way around: it fetches candidate posts as JSON and then applies X's advanced-search operators locally, in about 800 lines of Go you can read and test. It has three commands:
explainshows how a query is split between "what to fetch" and "what to filter"searchprints matching posts as a tablewatchremembers what it has already reported and appends only new matches to a JSONL file, so it can run from cron
Everything below ran on November 27, 2026 (04:10-04:45 UTC) with Go 1.27.3 on a Linux server.
Read this first
X's Terms of Service prohibit scraping. The X Terms of Service (effective October 9, 2026) say that "crawling or scraping the Services in any form, for any purpose without our prior written consent is expressly prohibited", and that you may not access or search the Services "by any means (automated or otherwise) other than through our currently available, published interfaces".
The catch-all group in x.com/robots.txt is User-agent: * / Disallow: /. Review the terms and the legal risk for your use case and location before you run anything here.
If the official X API covers your job, use it: recent search (last 7 days) and full-archive search are both there, billed pay-per-use (X's pricing page listed $0.005 per post read in November 2026). Keep volumes small, and don't republish other people's posts or build profiles of individuals. The tables below mask the handles of private persons.
Step 1: What a logged-out Go client gets
Before writing a parser, check what X sends to a plain HTTP client:
// probe: what X answers to a logged-out client in 2026. Go standard library only.
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"strings"
"time"
)
func main ( ) {
client := & http . Client { Timeout : 20 * time . Second ,
// Show redirects instead of following them.
CheckRedirect : func ( * http . Request , [ ] * http . Request ) error { return http . ErrUseLastResponse } ,
}
urls := [ ] string {
"https://x.com/search?q=golang%20min_faves%3A100&f=live" ,
"https://api.x.com/2/tweets/search/recent?query=golang" ,
"https://syndication.twitter.com/srv/timeline-profile/screen-name/golang" ,
"https://x.com/robots.txt" ,
}
for _ , u := range urls {
req , _ := http . NewRequest ( "GET" , u , nil )
req . Header . Set ( "User-Agent" , "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36" )
resp , err := client . Do ( req )
if err != nil { fmt . Printf ( "%s\nerror: %v\n" , u , err ) continue }
body , _ := io . ReadAll ( io . LimitReader ( resp . Body , 1 << 20 ) )
resp . Body . Close ( )
fmt . Printf ( "%s\nHTTP %d" , u , resp . StatusCode )
if loc := resp . Header . Get ( "Location" ) ; loc != "" { fmt . Printf ( " -> %.70s..." , loc ) }
fmt . Println ( )
if strings . HasSuffix ( u , "robots.txt" ) {
// Print the catch-all group: the rules for everyone who isn't a named crawler.
sc := bufio . NewScanner ( strings . NewReader ( string ( body ) ) )
inStar := false
for sc . Scan ( ) {
line := strings . TrimSpace ( sc . Text ( ) )
if strings . HasPrefix ( line , "User-agent:" ) { inStar = line == "User-agent: *" }
if inStar && line != "" && ! strings . HasPrefix ( line , "#" ) { fmt . Println ( "" , line ) }
}
} else if len ( body ) > 0 { fmt . Printf ( "%.100s\n" , strings . Join ( strings . Fields ( string ( body ) ) , " " ) ) }
}
}
https://x.com/search?q=golang%20min_faves%3A100&f=live
HTTP 307 -> /i/jf/onboarding/web?redirect_after_login=%2Fsearch%3Ff%3Dlive%26q%3Dg...
https://api.x.com/2/tweets/search/recent?query=golang
HTTP 401 { "title": "Unauthorized", "type": "about:blank", "status": 401, "detail": "Unauthorized" }
https://syndication.twitter.com/srv/timeline-profile/screen-name/golang
HTTP 429 Rate limit exceeded
https://x.com/robots.txt
HTTP 200 User-agent: * Disallow: / Disallow: /i/u Crawl-delay: 1 Sitemap: https://x.com/sitemap.xml Sitemap: https://x.com/sitemaps/finance0
Four doors, four answers:
x.com/searchanswers with a 307 to the login flow. The advanced-search form just builds a/search?q=...URL like this one, so it is behind the same wall.api.x.com/2/tweets/search/recentis the official API. Without a bearer token you get 401. With one you pay per post returned.- The old syndication timeline (what embedded profile timelines used) is rate-limited to death: 429 on the first request from this machine.
robots.txtlists rules for named search crawlers and then closes everything else withDisallow: /.
So "just scrape the search page" is out, and I'm not going to show login automation or cookie reuse. That is exactly what the terms forbid, and the accounts get locked anyway.
What's left is to fetch posts from a data source and do the search part yourself.
Step 2: Where the candidate posts come from
The tool reads X through ScrapeAtlas*, using two endpoints:
/v1/twitter/user-tweets?handle=golang&trim=truereturns an account's latest posts (14-20 per account in my runs) with views, likes, retweets, replies, quotes and the full legacy object.sinceanduntilnarrow it down, but only inside that latest window: asking@golangfor September 2026 returned zero posts with the warninglatest_window_limited, even though the account posted in September. It costs 1 credit./v1/twitter/search/posts?query=...finds posts by keyword through a web index, not through X's own search. Results come back in relevance order, a handful per page, with a cursor likeatlas:2orserper:3for the next page. It costs 2 credits per page. In my runs the cursor ran out after 3-4 pages, at roughly 10-20 unique posts per keyword. Operators are not supported there:from:golang since:2026-11-01came back with zero posts.
That split decides the design. A from: query is answered precisely from timelines. Everything else is discovery: the web index proposes posts, the local filter decides. You will not get "every post that mentions X". You'll get a relevant sample that is filtered exactly.
Every response also has a coverage object (complete, order, warnings). The tool prints the warnings on every run, because "0 matches" means something different when the source says complete: false.
Step 3: A client with a disk cache
While you tune a query you run the same fetches over and over. Each response is cached on disk for 30 minutes, keyed by the full URL, so re-running a filter costs nothing. 429 and 5xx are retried with backoff (2s, 4s, 8s). Other errors stop the run instead of being silently skipped.
package main
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
const apiBase = "https://api.scrapeatlas.com"
type Client struct { key string
http * http . Client
cacheDir string
cacheTTL time . Duration
Calls int // paid requests actually sent (cache hits are free)
}
// envelope holds the fields every ScrapeAtlas twitter response shares.
type envelope struct { Success bool `json:"success"`
Status string `json:"status"`
Cursor * string `json:"cursor"`
Posts [ ] rawTweet `json:"posts"` // /search/posts
Tweets [ ] rawTweet `json:"tweets"` // /user-tweets
Error json . RawMessage `json:"error"`
Coverage struct { Source string `json:"source"`
Order string `json:"order"`
Complete bool `json:"complete"`
Warnings [ ] string `json:"warnings"` } `json:"coverage"` }
func NewClient ( ) ( * Client , error ) {
key := os . Getenv ( "SCRAPEATLAS_API_KEY" )
if key == "" { return nil , errors . New ( "set SCRAPEATLAS_API_KEY" ) }
return & Client { key : key , http : & http . Client { Timeout : 60 * time . Second } , cacheDir : "cache" , cacheTTL : 30 * time . Minute } , nil }
func ( c * Client ) Get ( path string , params url . Values ) ( * envelope , error ) {
u := apiBase + path + "?" + params . Encode ( )
sum := sha1 . Sum ( [ ] byte ( u ) )
cacheFile := filepath . Join ( c . cacheDir , hex . EncodeToString ( sum [ : 8 ] ) + ".json" )
if st , err := os . Stat ( cacheFile ) ; err == nil && time . Since ( st . ModTime ( ) ) < c . cacheTTL {
if b , err := os . ReadFile ( cacheFile ) ; err == nil { return decode ( b ) } }
var lastErr error
for attempt := 0 ; attempt < 4 ; attempt ++ {
if attempt > 0 { time . Sleep ( time . Duration ( 1 << attempt ) * time . Second ) // 2s, 4s, 8s }
req , _ := http . NewRequest ( "GET" , u , nil )
req . Header . Set ( "x-api-key" , c . key )
resp , err := c . http . Do ( req )
if err != nil { lastErr = err
continue }
b , err := io . ReadAll ( resp . Body )
resp . Body . Close ( )
c . Calls ++
if err != nil { lastErr = err
continue }
if resp . StatusCode == 429 || resp . StatusCode >= 500 { lastErr = fmt . Errorf ( "%s: HTTP %d" , path , resp . StatusCode )
continue }
if resp . StatusCode != 200 { return nil , fmt . Errorf ( "%s: HTTP %d: %.300s" , path , resp . StatusCode , b ) }
env , err := decode ( b )
if err != nil { return nil , fmt . Errorf ( "%s: %w" , path , err ) }
os . MkdirAll ( c . cacheDir , 0o755 )
os . WriteFile ( cacheFile , b , 0o644 )
return env , nil }
return nil , lastErr }
func decode ( b [ ] byte ) ( * envelope , error ) {
var env envelope
if err := json . Unmarshal ( b , & env ) ; err != nil { return nil , err }
if ! env . Success { return nil , fmt . Errorf ( "success=false: %.300s" , env . Error ) }
return & env , nil }
Calls counts requests that actually went out, so the summary line can tell you what a run cost. A search page is 2 credits, so a 4-page search is 8 credits.
Step 4: Normalizing a tweet
Both endpoints return X's own GraphQL tweet shape. Some details matter for searching:
- Retweets are shells. The retweet object has
favorite_count: 0and text cut at 140 characters (RT @resend: We rebuilt our email API to Go.\n\nIt took 7 weeks and 140 PRs, and we've been running in production for weeks at roughly half thβ¦). The real text and media are inretweeted_status_result. - Long posts live in
note_tweet.legacy.full_textstops near 280 characters. In the saved@golangtimeline, 5 of 17 posts were longer than that. If you match keywords againstfull_text, a word in paragraph two never matches. And not every long post has a note: one of NASA's posts ended mid-sentence at 277 characters ("NASA stands ready to") with nonote_tweetat all. - Text is HTML-escaped.
>and&show up infull_text, so unescape before matching. - Timeline items have no author object with
trim=true. The url field (https://x.com/NASA/status/...) still has the handle in its original case.
package main
import (
"encoding/json"
"html"
"strconv"
"strings"
"time"
)
// Tweet is the flat shape the filter and the reports work on.
type Tweet struct { ID string `json:"id"`
Author string `json:"author"`
Created time . Time `json:"created"`
Text string `json:"text"`
Lang string `json:"lang"`
Faves int `json:"faves"`
Retweets int `json:"retweets"`
Replies int `json:"replies"`
Quotes int `json:"quotes"`
Views int `json:"views"`
ReplyTo string `json:"reply_to,omitempty"`
IsRetweet bool `json:"is_retweet,omitempty"`
IsQuote bool `json:"is_quote,omitempty"`
HasMedia bool `json:"has_media,omitempty"`
URLs [ ] string `json:"urls,omitempty"`
URL string `json:"url"` }
type rawUser struct { Result struct { Core struct { ScreenName string `json:"screen_name"` } `json:"core"`
Legacy struct { ScreenName string `json:"screen_name"` } `json:"legacy"` } `json:"result"` }
type rawLegacy struct { CreatedAt string `json:"created_at"`
FullText string `json:"full_text"`
Lang string `json:"lang"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
ReplyCount int `json:"reply_count"`
QuoteCount int `json:"quote_count"`
IsQuoteStatus bool `json:"is_quote_status"`
InReplyTo string `json:"in_reply_to_screen_name"`
Entities struct { URLs [ ] struct { ExpandedURL string `json:"expanded_url"` } `json:"urls"` } `json:"entities"`
ExtendedEntities struct { Media [ ] json . RawMessage `json:"media"` } `json:"extended_entities"`
RetweetedStatus * struct { Result rawTweet `json:"result"` } `json:"retweeted_status_result"` }
type rawTweet struct { TypeName string `json:"__typename"`
Tweet * rawTweet `json:"tweet"` // TweetWithVisibilityResults wraps the real tweet
RestID string `json:"rest_id"`
Core struct { UserResults rawUser `json:"user_results"` } `json:"core"`
Views struct { Count string `json:"count"` } `json:"views"`
Legacy rawLegacy `json:"legacy"`
NoteTweet * struct { // posts longer than 280 characters
Results struct { Result struct { Text string `json:"text"`
EntitySet struct { URLs [ ] struct { ExpandedURL string `json:"expanded_url"` } `json:"urls"` } `json:"entity_set"` } `json:"result"` } `json:"note_tweet_results"` } `json:"note_tweet"`
URL string `json:"url"` }
// normalize turns one ScrapeAtlas tweet object into a Tweet. Timeline items
// (trim=true) carry no author object: read it from the post URL, else use
// the handle the caller asked for.
func normalize ( r rawTweet , fallbackAuthor string ) ( Tweet , error ) {
if r . Tweet != nil { r = * r . Tweet }
l := r . Legacy
created , err := time . Parse ( time . RubyDate , l . CreatedAt )
if err != nil { return Tweet { } , err }
author := r . Core . UserResults . Result . Core . ScreenName
if author == "" { author = r . Core . UserResults . Result . Legacy . ScreenName }
if author == "" && strings . HasPrefix ( r . URL , "https://x.com/" ) { author , _ , _ = strings . Cut ( strings . TrimPrefix ( r . URL , "https://x.com/" ) , "/" ) }
if author == "" { author = fallbackAuthor }
views , _ := strcon
Comments
No comments yet. Start the discussion.