-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix: JSON based scrapers fail with Chrome CDP #7137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
wraithfive
wants to merge
5
commits into
stashapp:develop
Choose a base branch
from
wraithfive:fix/cdp-json-scraper-response
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
067aab4
Fix: CDP scrapers return HTML-wrapped JSON instead of raw response fo…
wraithfive 253f27e
Address review feedback: fix data race, condense condition, warn on f…
wraithfive fec26b9
Use a named mutex field, matching project convention
wraithfive e19b2aa
Add a unit test that catches the CDP JSON-document race
wraithfive 130c0df
Fix iframe JSON responses hijacking extraction for HTML CDP scrapers
wraithfive File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -253,6 +253,25 @@ func urlFromCDP(ctx context.Context, urlCDP string, driverOptions scraperDriverO | |
| var res string | ||
| headers := cdpHeaders(driverOptions) | ||
|
|
||
| // Track the main document response so that, if it turns out to be JSON, | ||
| // we can pull the raw response body via CDP's Network domain instead of | ||
| // reading the rendered DOM. Chrome's built-in JSON viewer wraps raw JSON | ||
| // responses in an HTML pretty-printer when navigated to directly, so | ||
| // OuterHTML on such a page returns HTML containing the JSON rather than | ||
| // the JSON itself. | ||
| var jsonRequestID network.RequestID | ||
| var isJSONDocument bool | ||
| chromedp.ListenTarget(ctx, func(ev interface{}) { | ||
| if ev, ok := ev.(*network.EventResponseReceived); ok { | ||
| if ev.Type == network.ResourceTypeDocument && !isJSONDocument { | ||
| if isJSONMimeType(ev.Response.MimeType) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These 2 conditions can be be condensed. |
||
| jsonRequestID = ev.RequestID | ||
| isJSONDocument = true | ||
| } | ||
| } | ||
| } | ||
| }) | ||
|
|
||
| if proxyUsesAuth(globalConfig.GetProxy()) { | ||
| _, user, pass := splitProxyAuth(globalConfig.GetProxy()) | ||
|
|
||
|
|
@@ -294,7 +313,20 @@ func urlFromCDP(ctx context.Context, urlCDP string, driverOptions scraperDriverO | |
| chromedp.Navigate(urlCDP), | ||
| chromedp.Sleep(sleepDuration), | ||
| setCDPClicks(driverOptions), | ||
| chromedp.OuterHTML("html", &res, chromedp.ByQuery), | ||
| chromedp.ActionFunc(func(ctx context.Context) error { | ||
| if isJSONDocument { | ||
| body, err := network.GetResponseBody(jsonRequestID).Do(ctx) | ||
| if err != nil { | ||
| // fall back to OuterHTML if the response body is no | ||
| // longer available (e.g. evicted from Chrome's cache) | ||
| logger.Debugf("[scraper] could not get raw response body for JSON document, falling back to OuterHTML: %v", err) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would making this a warning rather than a debug be better so people can see it in the logs easier? |
||
| return chromedp.OuterHTML("html", &res, chromedp.ByQuery).Do(ctx) | ||
| } | ||
| res = string(body) | ||
| return nil | ||
| } | ||
| return chromedp.OuterHTML("html", &res, chromedp.ByQuery).Do(ctx) | ||
| }), | ||
| printCDPCookies(driverOptions, "Cookies set"), | ||
| ) | ||
|
|
||
|
|
@@ -361,6 +393,20 @@ func getRemoteCDPWSAddress(ctx context.Context, url string) (string, error) { | |
| return remote, err | ||
| } | ||
|
|
||
| // isJSONMimeType returns true if the given response MIME type indicates | ||
| // JSON content (e.g. "application/json", "application/ld+json", | ||
| // "text/json; charset=utf-8"), for deciding whether a CDP-fetched document | ||
| // should be read via its raw network response body rather than the | ||
| // rendered DOM. | ||
| func isJSONMimeType(mimeType string) bool { | ||
| mimeType, _, _ = strings.Cut(mimeType, ";") | ||
| mimeType = strings.TrimSpace(strings.ToLower(mimeType)) | ||
|
|
||
| return mimeType == "application/json" || | ||
| strings.HasSuffix(mimeType, "+json") || | ||
| mimeType == "text/json" | ||
| } | ||
|
|
||
| func cdpHeaders(driverOptions scraperDriverOptions) map[string]interface{} { | ||
| headers := map[string]interface{}{} | ||
| if driverOptions.Headers != nil { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package scraper | ||
|
|
||
| import "testing" | ||
|
|
||
| func TestIsJSONMimeType(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| mimeType string | ||
| want bool | ||
| }{ | ||
| {"plain json", "application/json", true}, | ||
| {"json with charset", "application/json; charset=utf-8", true}, | ||
| {"json with charset and spacing", "application/json; charset=UTF-8", true}, | ||
| {"structured syntax suffix", "application/ld+json", true}, | ||
| {"uppercase", "APPLICATION/JSON", true}, | ||
| {"text/json", "text/json", true}, | ||
| {"html", "text/html", false}, | ||
| {"html with charset", "text/html; charset=utf-8", false}, | ||
| {"plain text", "text/plain", false}, | ||
| {"empty", "", false}, | ||
| {"contains json as substring but isn't json", "application/jsonp", false}, | ||
| {"contains json as substring but isn't json 2", "multipart/json-form-data", false}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got := isJSONMimeType(tt.mimeType) | ||
| if got != tt.want { | ||
| t.Errorf("isJSONMimeType(%q) = %v, want %v", tt.mimeType, got, tt.want) | ||
| } | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These are written on chromedps event processing georoute but read from chromedp.Run georoute and they're not synced. I think this could create a race.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch