0
        #Searches in google for "How to Cook"

        driver.get('https://www.google.com/')
        time.sleep(2)
        driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input') \
            .send_keys("How to Cook")
        time.sleep(3)
        driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input') \
            .send_keys(Keys.ENTER)
        # driver.find_element_by_xpath('//*[@id="search"]')

        #Clicks on Random Link (the part I need help with)

        results = driver.find_elements_by_xpath("//div[@class='g']//div[@class='rc']//a[not(@class)]")
        for result in results:
            resultsList = result.get_attribute("href")
            print(resultsList)

So I am having some trouble with going to a random link. I have set up the process to go to google, search How to Cook, click enter, and then get all the links I want to choose from on that page and then print them out. I am struggling with how to take one of those links from the for loop and print that out, resulting in just one link being printed out instead of all of them. I would then just use that link and .get() to that. Thanks in advance!

1 Answers1

0
num1 = random.randint(0, len(results));
driver.get(results[num1].get_attribute("href"))
print(results[num1].get_attribute("href"))
Gaj Julije
  • 1,538
  • 15
  • 32
  • And just to confirm, you put all three of those lines within the for loop and replace out the two lines already in there? When I did that, It worked and loaded a random page, but I got an error: selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document – John Santoro Nov 08 '20 at 18:20
  • Please see: https://stackoverflow.com/questions/18225997/stale-element-reference-element-is-not-attached-to-the-page-document Probably your DOM changed. – Gaj Julije Nov 08 '20 at 18:24