Spis treści

As you might already know, the Oficjalny interfejs API miejsc Google is limited to 5 reviews per place only. Therefore developers are looking into scraping to have the ability to fetch all the reviews from any business on Google Maps.

Skrobanie Google ze wszystkimi jego zabezpieczeniami i dynamicznie renderującymi się stronami może być trudnym zadaniem. Na szczęście istnieje wiele narzędzi, które można wykorzystać do scrapowania recenzji w pythonie lub innym języku programowania. W tym wpisie na blogu zobaczysz dwa najbardziej powszechne narzędzia do skrobania recenzji Google: emulacja przeglądarki i Outscraper Platform. Każdy z nich jest wystarczający, aby uzyskać wszystkie recenzje z dowolnego wpisu z map.

Skrobanie recenzji Google w Pythonie przy użyciu przeglądarki do renderowania dynamicznej zawartości

Będziemy używać Selen to control the Chrome browser. The browser will render the dynamic pages of Google Reviews. To get started with building the reviews scraper with Selenium, we’ll need the following:

  1. Python 3+.
  2. Zainstalowana przeglądarka Chrome.
  3. Selenium 3.141.0+ (pakiet python).
  4. Sterownik Chrome (dla Twojego systemu operacyjnego).
  5. Parsel lub dowolna inna biblioteka do wyodrębniania danych z HTML jak Beautiful Soup.

Zainstaluj Selenium i inne pakiety

Zainstaluj pakiety Selenium i Parsel wykonując następujące polecenia. Parsela użyjemy później, gdy będziemy parsować treść z HTML.

				
					pip install selenium
pip install parsel # to extract data from HTML using XPath or CSS selectors
				
			

Start the Browser

Przed uruchomieniem sterownika upewnij się, że wykonałeś poprzednie kroki i masz ścieżkę do swojego pliku chromedriver. Zainicjuj sterownik za pomocą następującego kodu. Powinieneś zobaczyć, że otwiera się nowe okno przeglądarki.

				
					from selenium import webdriver


chromedrive_path = './chromedriver' # use the path to the driver you downloaded from previous steps
driver = webdriver.Chrome(chromedrive_path)
				
			

You might see the following on mac: “chromedriver cannot be opened because the developer cannot be verified.” To overcome this, control-click the chromedriver in Finder, choose Open from the menu and then click Open in the dialog that appears. You should see “ChromeDriver was started successfully” in the opened terminal windows. Close it, and after this, you will be able to start ChromeDriver from your code.

Pobierz wszystkie recenzje Strona

Once you start the driver, you are ready to open some pages. To open any page, use the “get” command.

				
					url = 'https://www.google.com/maps/place/Central+Park+Zoo/@40.7712318,-73.9674707,15z/data=!3m1!5s0x89c259a1e735d943:0xb63f84c661f84258!4m16!1m8!3m7!1s0x89c258faf553cfad:0x8e9cfc7444d8f876!2sTrump+Tower!8m2!3d40.7624284!4d-73.973794!9m1!1b1!3m6!1s0x89c258f1fcd66869:0x65d72e84d91a3f14!8m2!3d40.767778!4d-73.9718335!9m1!1b1?hl=en&hl=en'
driver.get(url)
				
			

Recenzje Parse

Po otwarciu strony zobaczysz w oknie Chrome stronę, która jest kontrolowana przez Twój kod. Możesz uruchomić następujący kod, aby uzyskać zawartość strony HTML z sterownika.

				
					page_content = driver.page_source
				
			

Aby wygodnie zobaczyć zawartość HTML, otwórz konsolę deweloperską w Chrome, otwierając Menu Chrome w prawym górnym rogu okna przeglądarki i wybierając Więcej narzędzi > Narzędzia deweloperskie. Teraz powinieneś być w stanie zobaczyć elementy swojej strony.

skrobanie recenzji google w pythonie
Finding Xpath to the Reviews We Want to Get With Developer Console

Zawartość strony HTML można przeanalizować za pomocą ulubionych narzędzi do parsowania. My użyjemy Parsel w tym poradniku.

				
					from parsel import Selector

response = Selector(page_content)
				
			

Przeprowadź iterację nad przeglądami.

				
					results = []

for el in response.xpath('//div/div[@data-review-id]/div[contains(@class, "content")]'):
    results.append({
        'title': el.xpath('.//div[contains(@class, "title")]/span/text()').extract_first(''),
        'rating': el.xpath('.//span[contains(@aria-label, "stars")]/@aria-label').extract_first('').replace('stars' ,'').strip(),
        'body': el.xpath('.//span[contains(@class, "text")]/text()').extract_first(''),
    })
    
print(results)
				
			

Output from the Google Reviews Crawler (shortened).

				
					[
  {
    'title': 'Wanda Garrett',
    'rating': '5',
    'body': 'Beautiful ✨ park with a family-friendly atmosphere! I had a great time here; seeing all of the animals and learning all of the interesting facts was a fantastic way to spend the day. The zoo is beautifully landscaped and surrounded by …'
  },
  {
    'title': 'Bernadette Bennett',
    'rating': '4',
    'body': 'Worth going for the seals! They are the main attraction and located in the center of the zoo. We watched a live feeding and it was great. The kids loved it. The zoo is well manicured surrounded by gorgeous gardens. Lots of benches to rest …'
  },
  {
    'title': 'Mary Cutrufelli',
    'rating': '3',
    'body': "So not gonna lie... We came from PA. My kid expected to see lions and hippos and zebra from Madagascar. None of that which is there. It's clean it's a nice zoo. I wouldn't go again though."
  },
  ...
]
				
			

Zatrzymaj przeglądarkę

It’s important to start and stop the driver before and after the scraping accordingly. It’s the same as opening and closing your browser before and after surfing the internet. Stop the browser by running the following code.

				
					driver.quit()
				
			

Despite the tricky HTML structure of Google Reviews, with Selenium and good knowledge of XPath and CSS selectors, you can achieve quite good results in scraping. This method of using a browser emulator should protect you from getting blocked. However, if you scale your application, consider using proxies to avoid unexpected problems.

Multiprocessing i inne zalecenia

Możliwe jest uruchamianie sterowników w trybie wieloprocesowym (nie wielowątkowym), ale każdy sterownik będzie zużywał jeden procesor. Upewnij się, że masz ich wystarczająco dużo.

Najprostszy sposób na scrapowanie recenzji Google w Pythonie

Wyciąganie danych z Google za pomocą przeglądarek ma swoje plusy i minusy. Wprawdzie można stworzyć scrapera samemu, ale podczas skalowania może to pociągnąć za sobą duże wydatki na wykorzystanie serwerów z ogromną ilością procesorów do obsługi emulacji przeglądarek. Dodatkowo, powinna być osoba, która utrzymuje crawlera i aktualizuje go podczas zmian w witrynie Google.

Używając Outscraper PlatformaAPIlub SDKs, Outscraper zapewnia najprostsze rozwiązanie dla firm i osób prywatnych, aby rozpocząć Scraping Recenzje z Google bez obsługi serwerów proxy, emulacji przeglądarki, i inwestowania w rozwój.

Skrobanie recenzji w Pythonie przy użyciu SDK

1. Będziesz potrzebował python3+ i to pakiet python. Zainstaluj pakiet, uruchamiając polecenie.

				
					pip install google-services-api
				
			

2. Pobierz swój klucz API z Strona profilu.

3. Zaimportuj pakiet i zainicjuj go kluczem.

4. Określ lokalizację, podając łącze, identyfikator miejsca lub nazwę.

				
					from outscraper import ApiClient


api_cliet = ApiClient(api_key='KEY_FROM_OUTSCRAPER')
response = api_cliet.google_maps_reviews(
    'https://www.google.com/maps/place/Do+or+Dive+Bar/@40.6867831,-73.9570104,17z/data=!3m2!4b1!5s0x89c25b96a0b10eb9:0xfe4f81ff249e280d!4m5!3m4!1s0x89c25b96a0b30001:0x643d0464b3138078!8m2!3d40.6867791!4d-73.9548217',
    language='en',
    limit=100
)
				
			

5. Wait a few seconds till the reviews are fetched.

				
					[
    {
        "name": "Do or Dive Bar",
        "full_address": "1108 Bedford Ave, Brooklyn, NY 11216, United States",
        "borough": "Bedford-Stuyvesant",
        "street": "1108 Bedford Ave",
        "city": "Brooklyn",
        "postal_code": "11216",
        "country_code": "US",
        "country": "United States of America",
        "us_state": "New York",
        "state": "New York",
        "plus_code": null,
        "latitude": 40.686779099999995,
        "longitude": -73.9548217,
        "time_zone": "America/New_York",
        "site": "https://www.doordivebedstuy.com/",
        "phone": "+1 917-867-5309",
        "type": "Bar",
        "rating": 4.5,
        "reviews": 425,
        "reviews_data": [
            {
                "google_id": "0x89c25b96a0b30001:0x643d0464b3138078",
                "autor_link": "https://www.google.com/maps/contrib/115539085325450648866?hl=en-US",
                "autor_name": "Sam Grjaznovs",
                "autor_id": "115539085325450648866",
                "autor_image": "https://lh3.googleusercontent.com/a-/AOh14GgxmEH7a10v6Bo8AFb6OkbyxxfIBPXbMYVAxeSIRA=c0x00000000-cc-rp-ba3",
                "review_text": "Cozy shin dig with an assortment of drinks. They have a strong specialty for 10bucks and merch too. They have out side dining as well as back yard area. Ask for Brandon every other Saturday. He\u2019s hella cute!",
                "review_img_url": "https://lh5.googleusercontent.com/p/AF1QipPNs8QvvdkBonV5wuxdoylFjLY3k7L6muepbDq-",
                "owner_answer": null,
                "owner_answer_timestamp": null,
                "owner_answer_timestamp_datetime_utc": null,
                "review_link": "https://www.google.com/maps/reviews/data=!4m5!14m4!1m3!1m2!1s115539085325450648866!2s0x0:0x643d0464b3138078?hl=en-US",
                "review_rating": 5,
                "review_timestamp": 1603781021,
                "review_datetime_utc": "10/27/2020 06:43:41",
                "review_likes": 0,
                "reviews_id": "7222934207919784056"
            },
            {
                "google_id": "0x89c25b96a0b30001:0x643d0464b3138078",
                "autor_link": "https://www.google.com/maps/contrib/110571545135018844510?hl=en-US",
                "autor_name": "Arabella Stephens",
                "autor_id": "110571545135018844510",
                "autor_image": "https://lh3.googleusercontent.com/a-/AOh14GisqDfheDO0Aq0cu1Z7YBTbzLyvSEvM3IMDKg3q=c0x00000000-cc-rp",
                "review_text": "Great atmosphere, always fun vibe and good beers. I live in the area and this is a very reliable standby. Would recommend to anyone who is not pretentious and likes a bit of clutter in their watering hole.",
                "review_img_url": "https://lh3.googleusercontent.com/a-/AOh14GisqDfheDO0Aq0cu1Z7YBTbzLyvSEvM3IMDKg3q",
                "owner_answer": null,
                "owner_answer_timestamp": null,
                "owner_answer_timestamp_datetime_utc": null,
                "review_link": "https://www.google.com/maps/reviews/data=!4m5!14m4!1m3!1m2!1s110571545135018844510!2s0x0:0x643d0464b3138078?hl=en-US",
                "review_rating": 5,
                "review_timestamp": 1614111762,
                "review_datetime_utc": "02/23/2021 20:22:42",
                "review_likes": 0,
                "reviews_id": "7222934207919784056"
            },
            {
                "google_id": "0x89c25b96a0b30001:0x643d0464b3138078",
                "autor_link": "https://www.google.com/maps/contrib/101725757133547547783?hl=en-US",
                "autor_name": "Jack Parker",
                "autor_id": "101725757133547547783",
                "autor_image": "https://lh3.googleusercontent.com/a-/AOh14GjFK9CLb8__u5PtJzH1rGuX4DVgPvjaEeIkSJnCNw=c0x00000000-cc-rp",
                "review_text": "All the bartenders are rad. Cheap drinks, and a nice backyard. They have space heaters, but I would still recommend bundling up if you plan on spending a while there. Jeopardy night is always fun too. Can\u2019t wait to sit inside again!",
                "review_img_url": "https://lh3.googleusercontent.com/a-/AOh14GjFK9CLb8__u5PtJzH1rGuX4DVgPvjaEeIkSJnCNw",
                "owner_answer": null,
                "owner_answer_timestamp": null,
                "owner_answer_timestamp_datetime_utc": null,
                "review_link": "https://www.google.com/maps/reviews/data=!4m5!14m4!1m3!1m2!1s101725757133547547783!2s0x0:0x643d0464b3138078?hl=en-US",
                "review_rating": 5,
                "review_timestamp": 1611947492,
                "review_datetime_utc": "01/29/2021 19:11:32",
                "review_likes": 0,
                "reviews_id": "7222934207919784056"
            },
            ...
        ]
]
				
			

Python package ► https://pypi.org/project/google-services-api
API ► https://app.outscraper.com/api-docs

Samouczek wideo

FAQ

Najczęściej zadawane pytania i odpowiedzi

Thanks to Outscraper’s Google Maps Reviews API, it is possible to scrape all Google Maps reviews. Outscraper API services allow you to scrape without any limits.

There is an API service for Google Maps reviews. This is Outscraper’s Google Maps Reviews API. Thanks to Outscraper services, you can export and download all Google Maps reviews.

Reviews can be scraped with Python and Selenium. It is explained in detail in the article “Skrobanie wszystkich recenzji Google w Pythonie“.


Vlad

Kierownik projektu Linkedin