如何使用Selenium提取Google即搜即得答案

时间:2018-11-26 07:59:53

标签: python selenium selenium-chromedriver

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1024x768")
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)

def ask_google(query):

    # Search for query
    query = query.replace(' ', '+')

    driver.get('http://www.google.com/search?q=' + query)

    # Get text from Google answer box

    answer = driver.execute_script(
            "return document.elementFromPoint(arguments[0], arguments[1]);",
            350, 230).text

    return answer

我尝试在Selenium和chrome驱动程序的帮助下使用python提取google即时答案,但是当我运行它时会显示此错误

  

(1126 / 125608.919:ERROE:gpuprocess_transport_factory.cc <980> l丢失的用户界面   共享扩展IleuTools监听   ws://127.0.0.1:63320 / deutools / browser / 19540456-8dd5-4f7a-9   .25-fb3dd0E60000

enter image description here

我希望这是答案

ask_google("what is the time in US")

"4:36 PM"

ask_google("What is a car")

"a road vehicle, typically with four wheels, powered by an internal combustion engine and able to carry a small number of people.

有人可以帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

非致命错误,您可以忽略它

chrome_options.add_argument('log-level=3')

它没有在控制台中显示文本,也许是因为它缺少print()吗?并且需要采取其他措施才能使"a road vehicle, typically....见下文

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1024x768")
chrome_options.add_argument("--headless")
chrome_options.add_argument('log-level=3')
driver = webdriver.Chrome(chrome_options=chrome_options)

def ask_google(query):
    # Search for query
    query = query.replace(' ', '+')
    driver.get('http://www.google.com/search?q=' + query)

    # Get text from Google answer box
    answer = driver.execute_script("return document.elementFromPoint(350, 230);").text

    try:
        answer += "\n" + driver.find_element_by_xpath('//div[@data-dobid="dfn"]/span').text
    except: pass

    return answer

the_answer = ask_google("What is a car")
print(the_answer)
driver.close()