编辑: 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格式的定义结果以响应请求。