通过谷歌建议搜索

2024-09-29 00:20:56 发布

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

我试图添加到一个单一的文本谷歌建议,即我通过“最佳方式”谷歌建议“减肥”,所以我搜索“减肥”谷歌建议“在30天内”,所以我搜索“30天”等 Final是所有的建议加在一起,但是我得到了重复的结果,windowSize是应该在搜索中运行的字数

from selenium import webdriver
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from random import randint
options = webdriver.ChromeOptions()
options.add_argument('--user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"')
options.add_argument('headless')
driver=webdriver.Chrome(executable_path="/home/timmy/Python/chromedriver",chrome_options=options)
driver.get("https://www.google.com/ncr")
modifiedSearch="best way"
windowSize=2
z=1
Final=modifiedSearch
desiredInput=100
while len(Final)<desiredInput:
    temp3=modifiedSearch
    Search=driver.find_element_by_name("q")
    Search.clear()
    temp='"'+modifiedSearch+'"'
    Search.send_keys(temp)
    sleep(0.5)
    temp2='//*[@id="tsf"]/div[2]/div/div[2]/div[2]/ul/li[2]/div[1]/div/span'
    try:
        modifiedSearch = driver.find_element_by_xpath('/html/body/div/div[3]/form/div[2]/div/div[2]/div[2]/ul/li[1]/div[1]/div/span').text
        modifiedSearch = " ".join(modifiedSearch.split()[-windowSize:])
        if modifiedSearch.split()[windowSize-1]==temp3.split()[0]:
            print("xx")
            raise NoSuchElementException
    except NoSuchElementException:
        modifiedSearch = driver.find_element_by_xpath(temp2).text
        modifiedSearch = " ".join(modifiedSearch.split()[-windowSize:])
        print("mod: %s" % modifiedSearch)



    print(modifiedSearch)
    Final=Final+" "+modifiedSearch.split()[0]

driver.close()
print (Final)

输出:

best way lose weight weight weight weight weight weight weight weight weight weight weight weight weight

应该是这样的

最佳减肥方法

减重30天

30天提供夜间

注意:请注意,我正在搜索谷歌建议的最后两个词

我需要避免这些重复,输出应该是best way lose weight 30 days of night ...

请注意,我在“搜索建议”中使用了最后两个词(windowSize)

*我希望这个问题符合堆栈溢出条款。你知道吗


Tags: fromimportdivdriver建议finaloptionssplit
1条回答
网友
1楼 · 发布于 2024-09-29 00:20:56

你的代码按预期工作,但谷歌实际上给出了相同的结果!您可以通过注释您的行来验证这一点

#options.add_argument('headless')

再看看弹出的搜索结果,你就会发现事实上谷歌就是这样循环的那个。你也许可以尝试从结果列表中随机获取一个结果,或者增加你的窗口大小(或者两者都增加)来给Google更多的工作空间!你知道吗

相关问题 更多 >