我进行谷歌搜索的代码需要改进

时间:2017-02-06 11:43:39

标签: python search

这是我输入命令(变量com)的程序的一部分,如果命令包含谷歌或搜索它进行谷歌搜索。 有人可以帮助修复它,以便它也可以与包含谷歌的搜索一起使用(例如:'google google如何赚钱')。

if 'google' in com or 'search' in com:
    search=''
    foo=com.split()        
    for x in foo:
        if x!='google' and x!='search':
            search+='+'+x
    search=search[1:]
    print('googling:'+search)
    time.sleep(1)
    web.open('https://www.google.co.in/search?q='+search+'&oq='+search+'&aqs=chrome..69i57j69i60l2j69i61j69i60j69i61.306j0j9&s0ourceid=chrome&ie=UTF-8')

1 个答案:

答案 0 :(得分:0)

您要删除搜索请求中googlesearch的所有部分,无论它们位于com变量中的哪个位置。

只需将其拆分为first:rest,这样您就可以按住命令(仅cmd的第一个单词)并请求(cmd的其余单词):

com = 'google how google makes money'
url = 'https://www.google.com/search?q={query:s}'
pts = com.split()
cmd, qry = pts[0], ' '.join(pts[1:])

然后是:

print(cmd)
>>> 'google'
print(qry)
>>> 'how google makes money'

然后,您可以照常执行查询。顺便说一下:您不需要提供完整的网址,包括您从浏览器中复制的所有令牌:

import requests
from bs4 import BeautifulSoup

if cmd in ['google', 'search']:
    res = requests.get(url.format(query=qry))
    sup = BeautifulSoup(res.text, 'html.parser')

    res_root = sup.find('div', id='ires')
    for entry in res_root.find_all('h3'):
        print(entry.text)

收率:

How Does Google Make Its Money? | Investopedia
The Business of Google (GOOG) | Investopedia
BBC iWonder - How does Google make money?
How does Google earn money? - Quora
How Google Makes Money? - Revenues & Profits
How Does Google Make Money? - Minterest
If Google is free, how does it make so much money? – Channel 4 ...
Four ways Google makes money outside of advertising - TechRepublic
Google - How (precisely) it profits from YouTube - STL Partners ...
How Google's Money-Making Machine, AdWords, Actually Works ...