Selenium搜索谷歌建议



我正在尝试将谷歌建议添加到单个文本中,即我正在传递"最佳方式"谷歌建议"减肥",所以我搜索"减肥"谷歌建议"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天黑夜

注意:p租赁通知,我正在搜索谷歌建议的最后两个词

我需要避免这些重复,以某种方式输出应该best way lose weight 30 days of night ...

请注意,我在"搜索建议"中使用了最后两个词(窗口大小),

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

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

#options.add_argument('headless')

然后只要看看弹出的搜索结果,你就会发现实际上谷歌就是这样循环的那个。您也许可以尝试从结果列表中获取随机结果,或者增加窗口大小(或两者兼而有之),以尝试为Google提供更多使用!

最新更新