使用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.com/python/
2
https://tutorialspoint.com/python3/
3
https://tutorialspoint.com/python_online_training/index.asp
4
https://tutorialspoint.com/python/python_overview.htm
5
https://tutorialspoint.com/python/python_loops.htm
6
https://tutorialspoint.com/python/python_pdf_version.htm
7
https://tutorialspoint.com/python/python_basic_syntax.htm
8
https://tutorialspoint.com/tutorialslibrary.htm
9
https://tutorialspoint.com/
10
https://tutorialspoint.com/django/
11
https://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

当我们尝试通过浏览器搜索时,我们会得到类似的结果:

如果我们希望直接通过浏览器获取查询搜索结果,而不是提供结果链接,则可以使用以下程序:

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”,它将弹出一个浏览器窗口,显示:

更新于:2020年6月30日

1000+ 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.