使用Python脚本进行谷歌搜索

34 投票
8 回答
98426 浏览
提问于 2025-04-16 05:15

有没有人能帮我写一个Python脚本,让它去搜索谷歌并打印出最顶尖结果的链接。

8 个回答

1

建议使用谷歌的API,虽然这个方法看起来有点丑陋……(这是使用谷歌API的另一种选择)如果你想的话,可以对内容进行过滤。

import os, urllib, sys
filename = 'http://www.google.com/search?' + urllib.urlencode({'q': ' '.join(sys.argv[1:]) })
cmd = os.popen("lynx -dump %s" % filename)
output = cmd.read()
cmd.close()
print output

它会准确地显示出你在谷歌上搜索某个东西时,浏览器应该显示的内容。

34

试试这个,使用起来非常简单:

https://pypi.python.org/pypi/google

文档:https://breakingcode.wordpress.com/2010/06/29/google-search-python/

Github链接:https://github.com/MarioVilas/google

安装这个Python包,使用起来就像这样简单:

# Get the first 5 hits for "google 1.9.1 python" in Google Pakistan
from google import search

for url in search('google 1.9.1 python', tld='com.pk', lang='es', stop=5):
    print(url)
25

也许可以这样做?

import urllib
import json as m_json
query = raw_input ( 'Query: ' )
query = urllib.urlencode ( { 'q' : query } )
response = urllib.urlopen ( 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&' + query ).read()
json = m_json.loads ( response )
results = json [ 'responseData' ] [ 'results' ]
for result in results:
    title = result['title']
    url = result['url']   # was URL in the original and that threw a name error exception
    print ( title + '; ' + url )

可以看看文档,地址是 http://docs.python.org/

[编辑] 由于AJAX API已经不再使用,你可以试试一个第三方服务,比如 SerpApi,他们提供了一个 Python库

撰写回答