목차

이미 알고 계시겠지만 공식 Google Places API 는 장소당 5개의 리뷰로만 제한됩니다. 따라서 개발자는 Google 지도의 모든 비즈니스에서 모든 리뷰를 가져올 수 있는 스크래핑 기능을 검토하고 있습니다.

모든 보호 기능과 동적으로 렌더링되는 페이지가 있는 Google을 스크래핑하는 것은 어려운 작업일 수 있습니다. 다행히도 파이썬이나 다른 프로그래밍 언어로 리뷰를 스크래핑하는 데 사용할 수 있는 도구가 많이 있습니다. 이 블로그 게시물에서는 Google 리뷰를 스크래핑하는 가장 일반적인 두 가지 도구인 브라우저 에뮬레이션과 Outscraper 플랫폼을 살펴봅니다. 각각은 지도에서 모든 목록의 모든 리뷰를 가져오는 데 충분합니다.

브라우저를 사용하여 동적 콘텐츠를 렌더링하여 Python에서 Google 리뷰 스크랩하기

우리는 다음을 사용합니다. 셀레늄 을 클릭하여 Chrome 브라우저를 제어합니다. 브라우저는 Google 리뷰의 동적 페이지를 렌더링합니다. 셀레늄으로 리뷰 스크레이퍼를 구축하기 시작하려면 다음이 필요합니다:

  1. Python 3+.
  2. Chrome 브라우저가 설치되어 있습니다.
  3. 셀레늄 3.141.0+(파이썬 패키지).
  4. Chrome 드라이버(사용 중인 OS용).
  5. 파셀 또는 기타 라이브러리를 사용하여 HTML에서 데이터를 추출할 수 있습니다.

셀레늄 및 기타 패키지 설치

다음 명령을 실행하여 셀레늄과 파셀 패키지를 설치합니다. 나중에 HTML에서 콘텐츠를 구문 분석할 때 Parsel을 사용할 것입니다.

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

브라우저 시작

드라이버를 시작하기 전에 이전 단계를 수행했는지, 크롬드라이버 파일 경로를 알고 있는지 확인하세요. 다음 코드로 드라이버를 초기화합니다. 새 브라우저 창이 열리는 것을 볼 수 있을 것입니다.

				
					from selenium import webdriver


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

Mac에서는 다음과 같은 메시지가 표시될 수 있습니다: "개발자를 확인할 수 없기 때문에 크롬드라이버를 열 수 없습니다." 이 문제를 해결하려면 Finder에서 크롬드라이버를 Control+클릭하고 메뉴에서 열기를 선택한 다음 나타나는 대화 상자에서 열기를 클릭하세요. 열린 터미널 창에 "ChromeDriver가 성공적으로 시작되었습니다"라는 메시지가 표시됩니다. 이 창을 닫으면 코드에서 크롬드라이버를 시작할 수 있습니다.

모든 리뷰 페이지 다운로드

드라이버를 시작하면 일부 페이지를 열 준비가 된 것입니다. 페이지를 열려면 "get" 명령을 사용합니다.

				
					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)
				
			

리뷰 분석

페이지가 열리면 코드에 의해 제어되는 페이지가 Chrome 창에 표시됩니다. 다음 코드를 실행하여 드라이버에서 HTML 페이지 콘텐츠를 가져올 수 있습니다.

				
					page_content = driver.page_source
				
			

HTML 콘텐츠를 편하게 보려면 브라우저 창의 오른쪽 상단 모서리에 있는 Chrome 메뉴를 열고 추가 도구 > 개발자 도구를 선택하여 Chrome에서 개발자 콘솔을 엽니다. 이제 페이지의 요소를 볼 수 있을 것입니다.

파이썬으로 구글 리뷰 스크랩하기
개발자 콘솔을 통해 얻고자 하는 리뷰에서 Xpath 찾기

자주 사용하는 구문 분석 도구를 사용하여 HTML 페이지의 콘텐츠를 구문 분석할 수 있습니다. 여기서는 파셀 를 클릭하세요.

				
					from parsel import Selector

response = Selector(page_content)
				
			

리뷰를 반복해서 살펴봅니다.

				
					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)
				
			

Google 리뷰 크롤러의 출력(단축).

				
					[
  {
    '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."
  },
  ...
]
				
			

브라우저 중지

스크래핑 전후에 드라이버를 적절히 시작하고 중지하는 것이 중요합니다. 인터넷 서핑을 하기 전과 후에 브라우저를 열고 닫는 것과 같은 이치입니다. 다음 코드를 실행하여 브라우저를 중지합니다.

				
					driver.quit()
				
			

Google 리뷰의 까다로운 HTML 구조에도 불구하고 셀레늄과 XPath 및 CSS 선택기에 대한 지식이 있으면 스크래핑에서 꽤 좋은 결과를 얻을 수 있습니다. 브라우저 에뮬레이터를 사용하는 이 방법을 사용하면 차단되는 것을 방지할 수 있습니다. 그러나 애플리케이션을 확장하는 경우 예기치 않은 문제를 피하기 위해 프록시 사용을 고려하세요.

멀티프로세싱 및 기타 권장 사항

멀티 스레딩이 아닌 멀티 프로세싱으로 드라이버를 실행할 수 있지만 각 드라이버는 하나의 CPU를 소비합니다. 드라이버가 충분한지 확인하세요.

파이썬으로 구글 리뷰를 스크랩하는 가장 쉬운 방법

브라우저를 사용하여 Google에서 데이터를 추출하는 데는 장단점이 있습니다. 스크레이퍼를 직접 개발할 수 있지만, 확장 시 브라우저 에뮬레이션을 처리하기 위해 막대한 양의 CPU가 탑재된 서버를 사용해야 하므로 비용이 많이 들 수 있습니다. 또한 크롤러를 유지 관리하고 Google 사이트 변경 시 업데이트하는 담당자가 있어야 합니다.

사용하여 Outscraper 플랫폼API또는 SDK, Outscraper는 기업과 개인이 프록시, 브라우저 에뮬레이션, 개발 투자 없이도 Google에서 리뷰 스크래핑을 시작할 수 있는 가장 쉬운 솔루션을 제공합니다.

SDK를 사용하여 파이썬에서 리뷰 스크랩하기

1. python3+ 및 이것이 필요합니다. 파이썬 패키지. 명령을 실행하여 패키지를 설치합니다.

				
					pip install google-services-api
				
			

2. API 키 가져오기 프로필 페이지.

3. 패키지를 임포트하고 키로 초기화합니다.

4. 링크, 장소 ID 또는 이름을 입력하여 위치를 지정합니다.

				
					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. 리뷰가 가져올 때까지 몇 초간 기다립니다.

				
					[
    {
        "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"
            },
            ...
        ]
]
				
			

파이썬 패키지 ► https://pypi.org/project/google-services-api
API ► https://app.outscraper.com/api-docs

비디오 튜토리얼

자주하는 질문

가장 자주 묻는 질문과 답변

Outscraper의 구글 지도 리뷰 API 덕분에 모든 구글 지도 리뷰를 스크랩할 수 있습니다. Outscraper API 서비스를 사용하면 제한 없이 스크랩할 수 있습니다.

구글 지도 리뷰를 위한 API 서비스가 있습니다. Outscraper의 구글 지도 리뷰 API입니다. Outscraper 서비스 덕분에 모든 Google 지도 리뷰를 내보내고 다운로드할 수 있습니다.

리뷰는 파이썬과 셀레늄으로 스크랩할 수 있습니다. " 문서에 자세히 설명되어 있습니다.파이썬으로 모든 Google 리뷰 스크래핑“.


Vlad

프로젝트 관리자 링크드인