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

2024-06-30 16:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的程序的一部分,您可以在其中输入一个命令(变量com),如果该命令包含google或search,它将执行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')

Tags: orandin命令程序comforsearch
1条回答
网友
1楼 · 发布于 2024-06-30 16:01:30

您正在从搜索请求中删除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'

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

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 ...

相关问题 更多 >