Currently using Selenium+ Python and this code:
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()`
as my code.
What Happens: Goes to Google and types in the words and hits search. Scrolls down a bit and then it clicks the first link
What I want: I want to be able to click a random link from the search result page
How to do this?
Edit: This is what I meant when I said unnecessary:
Unnecessary 1: https://imgur.com/a/70qz89x
These are the only results I want:
This: https://imgur.com/a/eTatFV9
解决方案
As per your question to click() on a random link from google search results, as per your code trial if you invoke window.scrollTo(0, 873) and then invoke click() as in:
find_element(By.XPATH, '(//h3)[3]/a').click()`
Selenium will still try to attempt click() on the first match, which may not be your desired usecase.
Solution
Inorder to click() on a random link from google search results, you can create a List out of the search results and then generate a Random Number and invoke click() through an index as follows:
Code Block:
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()
Console Output:
4