有没有办法从谷歌搜索中提取问题的答案



我实际上正在开发一个类似于JARVIS的AI。我想从谷歌上抓取答案,这样当我从我的人工智能中提问时;它将说出这个问题的答案。例如,如果我搜索谷歌";谷歌属于哪个国家"谷歌只是简单地说"加利福尼亚"。我尝试了一个谷歌模块来提取使用这个类的信息:

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()
  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/101.0.4951.67 Safari/537.36'
}
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搜索引擎结果API来实现同样的目的。这是一个付费的API免费计划。使用搜索查询检查操场。

要集成的代码:

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工作。

最新更新