Fix scraping multiple ads (#126)

Upstream has changed their content generation system. When using the same http client, the first page looks as we expect it, but subsequent pages look totally different. I can't find out why that is, but it's not an issue of this tool.

So, the "fix" is to abandon client reuse and re-initialize a new client for every http request. However, the image fetcher keeps resusing the client.

Co-authored-by: Thomas von Dein <tom@vondein.org>
Reviewed-on: https://codeberg.org/scip/kleingebaeck/pulls/126
This commit is contained in:
T. von Dein
2026-10-12 21:29:49 +02:00
parent 0d5ee0b485
commit d9f2f0a712
15 changed files with 251 additions and 69 deletions

View File

@@ -24,7 +24,11 @@ import (
"log/slog"
"net/http"
"net/http/cookiejar"
"net/http/httputil"
"net/url"
"os"
"strings"
"sync"
)
// convenient wrapper to fetch some web content
@@ -34,12 +38,25 @@ type Fetcher struct {
Cookies []*http.Cookie
}
// Pos is a counter for debug output file names
type Pos struct {
sync.Mutex
pos int
}
var pos *Pos
func NewFetcher(conf *Config) (*Fetcher, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, fmt.Errorf("failed to create a cookie jar obj: %w", err)
}
if pos == nil {
pos = &Pos{}
}
return &Fetcher{
Client: &http.Client{
Transport: &loggingTransport{}, // implemented in http.go
@@ -82,9 +99,43 @@ func (f *Fetcher) Get(uri string) (io.ReadCloser, error) {
slog.Debug("got cookies?", "cookies", res.Cookies())
f.Cookies = res.Cookies()
if err := f.Dump(res); err != nil {
return nil, err
}
return res.Body, nil
}
func (f *Fetcher) Dump(res *http.Response) error {
if f.Config.Debug && strings.Contains(res.Header.Get("Content-Type"), "text/html") {
// => dump content
pos.Lock()
defer pos.Unlock()
pos.pos++
dump, err := httputil.DumpResponse(res, true)
if err != nil {
return err
}
file := fmt.Sprintf("out%d.html", pos.pos)
fd, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
if _, err := fd.Write(dump); err != nil {
return err
}
slog.Debug("dump content", "file", file)
}
return nil
}
// fetch an image
func (f *Fetcher) Getimage(uri string) (io.ReadCloser, error) {
slog.Debug("fetching ad image", "uri", uri)