Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬(Python) 코드로 구글 검색 자동화하기

이 글에서는 파이썬 코드를 사용해 구글 검색을 수행하는 방법을 알아봅니다. 파이썬 프로젝트를 진행하면서 웹에서 데이터를 가져와야 하거나, 검색 결과를 프로젝트 내부에서 활용해야 할 때 이 기법이 매우 유용합니다.

사전 준비 사항

  • 시스템에 파이썬이 설치되어 있어야 합니다.
  • google 모듈을 설치해야 합니다. pip를 사용하면 간단하게 설치할 수 있습니다.
C:\Users\rajesh>python -m pip install google
Collecting google
Downloading https://files.pythonhosted.org/packages/c8/b1/887e715b39ea7d413a06565713c5ea0e3132156bd6fc2d8b165cee3e559c/google-2.0.1.tar.gz
Requirement already satisfied: beautifulsoup4 in c:\python\python361\lib\site-packages (from google) (4.6.0)
Installing collected packages: google
Running setup.py install for google ... done
Successfully installed google-2.0.1

위의 준비 사항이 모두 완료되었다면, 이제 파이썬 코드로 구글 검색을 수행할 수 있습니다.

검색 결과 링크 가져오기

아래 프로그램은 사용자가 특정 키워드(예: "AI in python" 또는 "Tutorialspoint")를 검색하고, 구글 검색 결과 상위 10개의 링크를 파이썬 프로젝트에서 활용하고자 하는 경우의 예시입니다.

# 파이썬 코드로 구글 검색 수행하기
class Gsearch_python:
    def __init__(self,name_search):
        self.name = name_search
    def Gsearch(self):
        count = 0
        try :
            from googlesearch import search
        except ImportError:
            print("No Module named 'google' Found")
        for i in search(query=self.name,tld='co.in',lang='en',num=10,stop=1,pause=2):
            count += 1
            print (count)
            print(i + '\n')
if __name__=='__main__':
    gs = Gsearch_python("Tutorialspoint Python")
    gs.Gsearch()

실행 결과

1
https://www.tutorialspoint.com/python/
2
https://www.tutorialspoint.com/python3/
3
https://www.tutorialspoint.com/python_online_training/index.asp
4
https://www.tutorialspoint.com/python/python_overview.htm
5
https://www.tutorialspoint.com/python/python_loops.htm
6
https://www.tutorialspoint.com/python/python_pdf_version.htm
7
https://www.tutorialspoint.com/python/python_basic_syntax.htm
8
https://www.tutorialspoint.com/tutorialslibrary.htm
9
https://www.tutorialspoint.com/
10
https://www.tutorialspoint.com/django/
11
https://www.tutorialspoint.com/numpy
12
https://www.quora.com/I-have-learned-Python-from-Tutorials-Point-What-should-I-do-to-learn-more-topics-so-that-I-can-have-more-advantages-on-my-interviews
13
https://www.pdfdrive.com/python-tutorial-tutorials-point-e10195863.html

브라우저에서 직접 동일한 키워드를 검색했을 때도 비슷한 결과를 얻을 수 있습니다.

검색 결과를 브라우저로 바로 열기

링크 목록 대신 검색 결과를 브라우저에서 바로 확인하고 싶다면, 아래 프로그램처럼 webbrowser 모듈을 함께 활용하면 됩니다.

from googlesearch import *
import webbrowser
# 실행 시점에 검색어를 입력받습니다
query = input("Input your query:")
#iexplorer_path = r'C:\Program Files (x86)\Internet Explorer\iexplore.exe %s'
chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
webbrowser.open("https://google.com/search?q=%s" % query)

실행 결과

>>>
=============== RESTART: C:/Python/Python361/google_search1.py ===============
Input your query:Tutorialspoint

위 예제에서는 "tutorialspoint"라는 검색어를 입력했으며, 실행하면 브라우저 창이 자동으로 팝업되며 해당 검색 결과 페이지가 열립니다.

이처럼 googlesearch 모듈을 활용하면 몇 줄의 코드만으로 구글 검색을 자동화할 수 있습니다. 단, 과도한 요청은 구글의 접속 제한 정책에 걸릴 수 있으므로 pause 옵션을 적절히 설정해 요청 간격을 조절하는 것이 좋습니다.