forked from ScrapeAlchemist/brightdata-hack-pack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_serp_api.py
More file actions
70 lines (57 loc) · 2 KB
/
Copy path02_serp_api.py
File metadata and controls
70 lines (57 loc) · 2 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
69
70
"""
Bright Data SERP API — Get search engine results without being blocked.
Returns raw HTML or parsed search results from Google, Bing, and other engines.
Setup:
1. Get your API key from https://brightdata.com/cp/setting/users
2. Find your SERP zone name from the control panel
3. Set environment variables:
export BRIGHTDATA_API_KEY="your_api_key"
export BRIGHTDATA_SERP_ZONE="your_serp_zone_name"
Usage:
python 02_serp_api.py
"""
import os
import json
from urllib.parse import urlencode
import requests
API_KEY = os.environ["BRIGHTDATA_API_KEY"]
SERP_ZONE = os.environ.get("BRIGHTDATA_SERP_ZONE", "serp_api1")
def search_google(query: str, num_results: int = 10) -> str:
"""Search Google and get raw HTML results."""
search_url = f"https://www.google.com/search?{urlencode({'q': query, 'num': num_results})}"
response = requests.post(
"https://api.brightdata.com/request",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json={
"zone": SERP_ZONE,
"url": search_url,
"format": "raw",
},
timeout=60,
)
response.raise_for_status()
return response.text
def search_google_parsed(query: str, num_results: int = 10) -> dict:
"""Search Google and get parsed JSON results (organic, ads, etc.)."""
search_url = f"https://www.google.com/search?{urlencode({'q': query, 'num': num_results})}"
response = requests.post(
"https://api.brightdata.com/request",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json={
"zone": SERP_ZONE,
"url": search_url,
"format": "json",
},
timeout=60,
)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
results = search_google_parsed("best python web scraping libraries")
print(json.dumps(results, indent=2)[:2000])