小编典典

如何通过Selenium和Python从Google搜索结果中单击随机链接

selenium

当前使用Selenium + Python和以下代码:

browser.get('http://www.google.com')
search = browser.find_element_by_name('q')
search.send_keys("how to search the internet")
search.send_keys(Keys.RETURN) # hit return after you enter search text
time.sleep(5) # sleep for 5 seconds so you can see the results
browser.execute_script("window.scrollTo(0, 873)") 
time.sleep(2)
browser.find_element(By.XPATH, '(//h3)[3]/a').click()`

作为我的代码。

发生什么:转到Google并输入单词并点击搜索。向下滚动一点,然后单击第一个链接

我想要的是:我希望能够从搜索结果页面中单击随机链接

这该怎么做?

编辑:这就是我说不必要的意思:不必要的1:https
://imgur.com/a/70qz89x

不必要的2:https :
//imgur.com/a/8WWvcnC

这些是我想要的唯一结果:这:https :
//imgur.com/a/eTatFV9


阅读 449

收藏
2020-06-26

共1个答案

小编典典

根据您的问题,click()从Google搜索结果中随机链接到您,按照您的 代码试用, 如果您调用window.scrollTo(0, 873),然后按以下方式调用click()

find_element(By.XPATH, '(//h3)[3]/a').click()`

Selenium 仍将尝试尝试click()第一个匹配,这可能不是您想要的用

序,以click()从谷歌搜索结果中的随机链接,你可以创建一个 列表 出来的 搜索结果 ,然后生成一个 随机数
,并调用click()通过 指标 如下:

  • 代码块:
        from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys 
    from random import randint

    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    browser=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    browser.get('http://www.google.com')
    search = browser.find_element_by_name('q')
    search.send_keys("selenium")
    search.send_keys(Keys.RETURN)
    my_search_list = WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[@class='r']/a[not(ancestor::div[@class='xIleA'])]")))
    myRandomNumber = randint(0, len(my_search_list))
    print(myRandomNumber)
    my_search_list[myRandomNumber].click()
  • 控制台输出:
    4
    
2020-06-26