使用Python程式碼執行Google搜尋?
在本文中,我們將嘗試使用Python程式碼進行Google搜尋,如果您正在進行Python專案並且需要從網路訪問某些資料,而搜尋結果(來自網路)將用於您的專案中,這將非常方便。
先決條件:
- 您的系統必須安裝Python。
- 安裝google模組。您可以使用pip安裝google模組,如下所示:
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
如果完成了以上所有先決條件,您可以編寫程式碼使用Python進行Google搜尋。
以下程式中,使用者想要搜尋特定關鍵字(例如:“Python中的AI”或“Tutorialspoint”),並希望將所有連結(假設為Google搜尋的前10個結果)用於他的Python專案。
# Performing google search using Python code 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://tutorialspoint.tw/python/ 2 https://tutorialspoint.tw/python3/ 3 https://tutorialspoint.tw/python_online_training/index.asp 4 https://tutorialspoint.tw/python/python_overview.htm 5 https://tutorialspoint.tw/python/python_loops.htm 6 https://tutorialspoint.tw/python/python_pdf_version.htm 7 https://tutorialspoint.tw/python/python_basic_syntax.htm 8 https://tutorialspoint.tw/tutorialslibrary.htm 9 https://tutorialspoint.tw/ 10 https://tutorialspoint.tw/django/ 11 https://tutorialspoint.tw/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
當我們嘗試透過瀏覽器搜尋時,我們會得到類似的結果:
如果我們希望直接透過瀏覽器獲取查詢搜尋結果,而不是提供結果連結,則可以使用以下程式:
from googlesearch import * import webbrowser #to search, will ask search query at the time of execution 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”,它將彈出一個瀏覽器視窗,顯示:
廣告