Repository navigation
Expand file tree
/
Copy pathsearch_ads.py
More file actions
68 lines (50 loc) · 1.62 KB
/
Copy pathsearch_ads.py
File metadata and controls
68 lines (50 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
"""
AdScrape — search and paginate Meta Ad Library results.
Docs: https://www.adscrape.in/docs
Signup: https://www.adscrape.in/signup
Usage:
export ADSCRAPE_API_KEY="sk_live_..."
python search_ads.py nike US
"""
from __future__ import annotations
import json
import os
import sys
import httpx
BASE_URL = "https://api.adscrape.in"
API_KEY = os.environ.get("ADSCRAPE_API_KEY", "")
def main() -> None:
if not API_KEY:
print("Set ADSCRAPE_API_KEY (get one at https://www.adscrape.in/settings/api-keys)", file=sys.stderr)
sys.exit(1)
query = sys.argv[1] if len(sys.argv) > 1 else "nike"
country = sys.argv[2] if len(sys.argv) > 2 else "US"
client = httpx.Client(
base_url=BASE_URL,
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
timeout=120.0,
)
page = client.post(
"/api/v1/search",
json={"query": query, "country": country, "max_results": 50},
).json()
total = 0
while True:
ads = page.get("ads") or []
total += len(ads)
print(f"page: +{len(ads)} ads (running total: {total})")
for ad in ads[:3]:
print(f" - {ad.get('page_name', '?')}: {ad.get('ad_archive_id')}")
if not page.get("has_more"):
break
page = client.post(
"/api/v1/search/next",
json={
"session_token": page["session_token"],
"page_size": 100,
},
).json()
print(json.dumps({"query": query, "country": country, "ads_collected": total}, indent=2))
if __name__ == "__main__":
main()