Choosing a proxy region is only the first step in cross-region analysis. Does a US exit automatically mean a US page with dollar prices? I would not make that assumption. Check the exit configuration, business region, language and currency separately before handing the data to pandas.
The task here is to read product samples for two regions, clean the fields, and summarize product counts and median amounts by region and currency. It does not depend on unauthorized account access or guessed destination region-switching APIs.
Treat region as both configuration and evidence
Use separate US and DE proxy settings. These are test groups, not a promise of current inventory. US_HOST, US_PORT, US_USER, US_PASS, and the corresponding DE_ variables must come from separately generated, verified configurations.
The region query parameter belongs to the owned endpoint used here. A real service might select region through a path, account, delivery address or cookie. Accept-Language expresses a language preference; it cannot force a response language or select the proxy exit.
If Gleam is an appropriate overseas residential proxy candidate, generate the region and session settings in its generator and supply the two configurations. This procedure applies to users and targets permitted by Gleam's service.
Define a comparable sample first
The endpoint returns items, with product ID, category, amount, currency, region and an offset-aware observation timestamp. The program keeps the latest observation for each product context and computes regional summaries. The product populations may differ between regions, so a difference between overall medians is not automatically a like-for-like price difference.
For like-for-like comparisons, align model, size, packaging, seller and tax conditions. Preserve the original currencies instead of silently converting them.
Complete collection and grouping code
Use Python3.11, Requests2.34.2 and pandas3.0.5. Save the program as main.py.
python3 -m pip install requests==2.34.2 pandas==3.0.5
python3 main.py
Before running, inject credentials through process configuration or a secret manager, not shared shell history. A single-region run needs PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS, DATA_URL, and REGION. For the two-region version, replace the proxy prefix with US_ and DE_; both regions use DATA_URL. The host is a hostname or IPv4 address without a scheme, and the port is an integer. The example uses an HTTP proxy with username/password authentication.
OUTPUT_DIR selects a directory that must not already exist; the default is analysis-output. The program stops rather than overwrite previous results. trust_env=False isolates environmental proxy settings and implicit CA paths. Set CA_FILE to an approved certificate bundle when required, keeping certificate verification enabled. Prepare the endpoint fields described above; the code does not execute page JavaScript.
import os, json, time, math
from pathlib import Path
from datetime import datetime, timezone
from urllib.parse import quote, urlsplit
import requests
import pandas as pd
def proxy_url(prefix="PROXY"):
host = os.environ[prefix + "_HOST"]
port = int(os.environ[prefix + "_PORT"])
user = quote(os.environ[prefix + "_USER"], safe="")
password = quote(os.environ[prefix + "_PASS"], safe="")
return f"http://{user}:{password}@{host}:{port}"
def collect(session, proxy, region):
url = os.environ["DATA_URL"]
if urlsplit(url).scheme not in {"http", "https"}:
raise ValueError("DATA_URL must be HTTP(S)")
with session.get(url, params={"region": region},
proxies={"http": proxy, "https": proxy},
timeout=(5, 15), allow_redirects=False) as r:
if not 200 <= r.status_code < 300:
raise ValueError(f"HTTP_{r.status_code}")
media = r.headers.get("Content-Type", "").split(";")[0].strip().lower()
if media != "application/json":
raise ValueError("content_type")
data = r.json()
if not isinstance(data, dict) or not isinstance(data.get("items"), list):
raise ValueError("items_schema")
return data["items"]
def clean(items):
required = ["id", "category", "amount", "currency", "region", "observed_at"]
good, bad = [], []
for index, item in enumerate(items):
try:
if not isinstance(item, dict):
raise ValueError("not_object")
if any(not isinstance(item.get(k), str) or not item[k].strip()
for k in required if k != "amount"):
raise ValueError("missing_text_field")
if isinstance(item.get("amount"), bool):
raise ValueError("invalid_amount")
amount = float(item["amount"])
if not math.isfinite(amount) or amount < 0:
raise ValueError("invalid_amount")
observed = datetime.fromisoformat(item["observed_at"].replace("Z", "+00:00"))
if observed.tzinfo is None:
raise ValueError("timezone_required")
good.append({**{k: item[k].strip() for k in required if k != "amount"},
"amount": amount, "observed_at": observed.astimezone(timezone.utc).isoformat()})
except (KeyError, TypeError, ValueError, OverflowError):
bad.append({"row": index, "reason": "invalid_record"})
frame = pd.DataFrame(good, columns=required)
if not frame.empty:
frame = frame.sort_values("observed_at", kind="stable").drop_duplicates(
["id", "region", "currency"], keep="last")
return frame, bad
def main():
out = Path(os.environ.get("OUTPUT_DIR", "analysis-output"))
out.mkdir(exist_ok=False)
session = requests.Session()
session.trust_env = False
if os.environ.get("CA_FILE"):
session.verify = os.environ["CA_FILE"]
try:
frames = []
for region in ["US", "DE"]:
session.cookies.clear()
session.headers["Accept-Language"] = {"US": "en-US", "DE": "de-DE"}[region]
rows = collect(session, proxy_url(region), region)
frame, rejected = clean(rows)
(out / f"{region}-rejects.json").write_text(json.dumps(rejected), encoding="utf-8")
if not frame.empty and not frame["region"].eq(region).all():
raise ValueError("region_mismatch")
frame.to_csv(out / f"{region}.csv", index=False)
frames.append(frame)
time.sleep(1)
all_rows = pd.concat(frames, ignore_index=True)
result = all_rows.groupby(["region", "currency"], as_index=False).agg(
products=("id", "nunique"), median_amount=("amount", "median"))
result.to_csv(out / "by-region-currency.csv", index=False)
print(result.to_string(index=False))
finally:
session.close()
if __name__ == "__main__":
try:
main()
except Exception as exc:
print("Stopped:", type(exc).__name__, "; check configuration, response and output directory.")
raise SystemExit(1)
Clear the right state when changing region
Cookies may preserve regional preferences. Clearing them before changing region reduces interference in this independent, non-login workflow. An authorized stateful workflow should instead have separate region-specific Sessions and maintain its required state deliberately.
The code sets en-US and de-DE language preferences, then verifies each record's returned region. A mismatch stops the analysis. Replacing that field with the requested region would manufacture a label rather than validate the returned observation.
US.csv and DE.csv retain separate regional detail. by-region-currency.csv groups by both dimensions. Similar numeric values do not make currencies or tax conditions interchangeable.
An empty sample is not a zero price
If a region has no valid observations, investigate whether the empty set is legitimate, then inspect filters, permissions and response structure. Do not turn “not collected” into “priced at zero.”
Observation timestamps are normalized to UTC for ordering. If business reports use a local calendar day, define that timezone separately, especially for observations around midnight. Establish the date convention before comparing trends.
I would inspect one product's region, language, currency and original page together first. If those details do not line up, a better chart only makes the inconsistency easier to see.
Frequently asked questions
Can one gateway serve two countries?
That depends on the provider configuration mechanism. Use separately generated and verified regional settings rather than infer the country from the gateway hostname.
Does clearing cookies guarantee the right region?
No. Paths, accounts, delivery addresses and destination rules may also affect the response. Validate the business result.
Why not average amounts from both regions together?
The currencies and product populations may differ. Group first, then align product and tax conditions before making a cross-region comparison.
Related reading
Sources
- requests.readthedocs.io — technical documentation
- pandas.pydata.org — technical documentation
- pandas.pydata.org — technical documentation
- www.ipgleam.net — technical documentation
- www.ipgleam.net — technical documentation
About the author
小张 — Cross-border data collection and overseas proxy author
Expertise: Cross-border product data; overseas proxy selection; region and session management; dynamic pages and browser collection; collection troubleshooting; provider trials and cost comparison