0

I need to extract the google search result snippets for Arabic queries. I am using serpapi in Python. My code is as follows:

from serpapi import GoogleSearch
import os

params = {
    "engine": "google",
    "q": "كاس العالم",
    "google_domain": "google.com.eg",
    "hl":"ar",
    "gl":"eg",
    
    "num": 20,
    "api_key": os.getenv("API_KEY")
}
client = GoogleSearch(params)
data = client.get_dict()

print("Organic results")

for result in data['organic_results']:
    print(f"""
Title: {result['title']}
Link: {result['link']}
Position: {result['position']}
Snippet: {result['snippet']}
""")

When I write the query in the Arabic language, an error appears as follows:

KeyError: 'organic_results'

What can I do in this case?

Sara Saad
  • 3
  • 2
  • Hey Sara, your `os.getenv(" ")` should become `os.getenv("API_KEY")` where `API_KEY` is a random name for your SerpApi API key (environment variable), it could be `i_like_cats`. Next, you need to pass it while running the script in the terminal: `API_KEY= python your_script.py` More on that topic: https://stackoverflow.com/questions/4906977/how-do-i-access-environment-variables-in-python and https://www.educative.io/answers/what-is-osgetenv-method-in-python – Dmitriy Zub Sep 21 '22 at 12:14
  • I'm sorry, I made a mistake while writing the code here, But I would have already written this command in my code..... And I edited the question... thank you – Sara Saad Sep 21 '22 at 13:47
  • @SaraSaad, does these search parameters work on the [SerpApi playground](https://serpapi.com/playground?q=%D9%83%D8%A7%D8%B3+%D8%A7%D9%84%D8%B9%D8%A7%D9%84%D9%85&location=Egypt&google_domain=google.com.eg&gl=eg&hl=ar&num=20&google_domain=google.com.eg) for you? – ilyazub Sep 21 '22 at 20:28
  • @SaraSaad Obvious but still want to ask since I don't see it in your code snippet. Did you import `serpapi`? `from serpapi import GoogleSearch`. If not imported, an error will be just like that. – Dmitriy Zub Sep 22 '22 at 05:30
  • @Dmitriy Zub, I imported serpapi in my code, but the same error appears... any suggestions?? – Sara Saad Sep 26 '22 at 07:29
  • @SaraSaad An obvious question, did you `pip install` it? [I've just tested your code snippet in the online IDE and it works as it should](https://replit.com/@DimitryZub1/UrbanGrossUnix#main.py). If you just run the code from the link, it will throw the same error because of the need to specify `API_KEY` in the Replit: `Secrets` -> `key-value`. – Dmitriy Zub Sep 27 '22 at 05:33

0 Answers0