【问题标题】:Is there a way to extract the answer to a question from google search有没有办法从谷歌搜索中提取问题的答案
【发布时间】:2021-01-19 07:26:25
【问题描述】:

我实际上正在研究类似于 JARVIS 的 AI。我想从谷歌那里抓取答案,这样当我向我的 AI 提出问题时;它会说出问题的答案。例如,如果我在 Google 上搜索“Google 属于哪个国家/地区?”谷歌只是说“加利福尼亚”。我尝试了一个谷歌模块来使用这个类来提取信息:

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')

gs = Gsearch_python('google belongs to which country')
gs.Gsearch()

【问题讨论】:

  • 查看 selenium 看看是否有帮助。您也可以简单地使用city to country 库来获取您感兴趣的国家/地区。
  • @AzyCrw4282 谢谢它的工作!但如果 jarvis 也能像谷歌助手那样说出结果会更好......

标签: python beautifulsoup google-search


【解决方案1】:
  1. 查看SelectorGadget Chrome 扩展程序。
  2. 通过 SelectorGadget 单击您要抓取的所需元素。
  3. 在您的代码中应用从 SelectorGadget 提供的 CSS 选择器。

将会变成:

# https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
answer = soup.select_one('.IZ6rdc').text

然后会变成这样:

from bs4 import BeautifulSoup
import requests

headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
    "Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

html = requests.get('https://www.google.com/search?q="Google belongs to which country?', headers=headers)
soup = BeautifulSoup(html.text, 'html.parser')

answer = soup.select_one('.IZ6rdc').text
print(answer)

# Output: United States of America

或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 来实现相同的目的。这是一个付费 API,可免费试用 5,000 次搜索。使用您的搜索查询检查 playground

要集成的代码:

from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "google",
  "q": "Google belongs to which country?",
}

search = GoogleSearch(params)
results = search.get_dict()

answer = results['answer_box']['answer']
print(answer)

# Output: American

免责声明,我为 SerpApi 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多