【问题标题】:How to perform a Google search and take the text result?如何执行 Google 搜索并获取文本结果?
【发布时间】:2014-02-09 03:14:42
【问题描述】:

想知道如何使用 Python 3 使用 Google 创建一些单词的字典(假设我输入一个单词,我希望 Python 采用 Google 能够给出的定义,然后存储或显示它)

我没有做太多编码,但我知道如何管理之后的单词。我对使用 urllib 和其他东西有点困惑。我只能在其他版本的 Python 上找到这方面的帮助,而我无法在 Python 3.3 上复制这些帮助。

编辑:是的,我想使用 Google,因为我喜欢它定义单词和短语的方式,我打算使用你提到的定义协议,icedtrees。

【问题讨论】:

标签: python dictionary urllib python-3.3 words


【解决方案1】:

编辑: Google 搜索似乎使用 AJAX 调用或其他方式获取其定义。以下解决方案将不起作用。


如果您在使用 urllib2 时遇到问题,我建议使用漂亮的 Python Requests 包,它更易于使用。

如果您绝对致力于获取 Google 定义而不是其他定义,我建议您使用 Google 搜索“定义”协议向页面发出 HTTP 请求。

例如:

https://www.google.com.au/search?q=define:test

然后您将保存 HTML 结果,然后将其解析为您需要的定义。 Python HTML 解析器的一些示例是HTMLParser 模块,还有BeautifulSoup。然而,这个解析操作看起来很简单,所以一个基本的正则表达式就足够了。所有定义存储如下:

<div style="display:inline" data-dobid="dfn"> # the order of the style and the data-dobid can change
    <span>definition goes here</span>
</div>

从 HTML 页面获取“测试”定义的正则表达式示例:

import re
definitions = re.findall(r'data-dobid="dfn".*?>.*?\<span>(.*?)</span>.*?</div>', html, re.DOTALL)

>>> len(definitions)
18
>>> definitions[0]
'a\n procedure intended to establish the quality, performance, or \nreliability of something, especially before it is taken into widespread \nuse.'
# Looks like you might need to remove the newlines
>>> definitions[5]
'the result of a medical examination or analytical procedure.'

作为旁注,还有一个Google Dictionary API,它可以为您提供JSON格式的定义结果以响应请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2017-10-14
    相关资源
    最近更新 更多