运行迭代搜索的Python脚本,并打印最佳结果和链接 [英] Python script that runs an iterating google search and prints top results and links

查看:152
本文介绍了运行迭代搜索的Python脚本,并打印最佳结果和链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个python脚本,将拉动前三个链接的连续谷歌搜索的标题和网址。例如,我希望能够谷歌3英里运行,4英里运行,5英里运行,并获得前三个链接。

我试着修改了一些我在这里找到的代码,它允许你打印用户输入的一个谷歌搜索的最高结果。



我把整个块放在一个for循环,并提出了一个具体的搜索,增加了与X.

 导入urllib 
导入json作为m_json

for x in range(3,5):
query ='x mile run'
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 results in results:
title = result ['title']
url = result ['url']#是在原来的URL,并抛出一个名称错误异常
p rint(title +';'+ url)

我不断收到意想不到的缩进错误,想知道是否有人可以帮忙。

解决方案

缩进错误只是缩进问题造成的。

这似乎很明显,但检查你的代码没有,说缩进的标签和空格的混合物。您的编辑器可能会显示与一个选项卡相同大小的4x空格。但是python没有这样看。



在Vi(或Vim)编辑器中,用空格替换标签的命令是:

 :1,$ s / [CTRL-v] [TAB] / / g 

如果没有,您可以手动删除并替换它们。使用空格或制表符,但是我建议使用空格。



复制和粘贴你的代码,它对我很有用,所以把它放在这里的行为已经规范了空间的混合和标签。


I want to write a python script that will pull the title and url of the top three links of successive google searches. For example, I want to be able to google "3 mile run", "4 mile run", and "5 mile run" and get the top three links from each.

I tried modifying some code I found on here that allows you to print the top results of one google search that the user inputs.

I put the entire block in a for loop and made the query a specific search that increases with x.

import urllib
import json as m_json

for x in range(3, 5): 
    query = 'x mile run'
    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 )

I keep getting unexpected indent errors though, and I was wondering if anyone could help.

解决方案

Indent errors are only caused by indentation problems.

It seems obvious, but check your code does not have, say a mixture of tabs and spaces for indenting. Your editor might show 4x spaces the same size as one tab. But python does not see it this way.

In the Vi (or Vim) editor, a command to replace the tabs with spaces would be:

:1,$s/[CTRL-v][TAB]/    /g

Failing that you can manually remove and replace them. With spaces or tabs, but I suggest spaces.

Copying and pasting your code, it works for me, so probably the act of putting it here has normalised the mix of spaces and tabs.

这篇关于运行迭代搜索的Python脚本,并打印最佳结果和链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆