How to Navigate to a New Webpage In Selenium?
Your first line:
for element in driver.find_elements_by_class_name('thumbnail'):
grabs all elements on the first page. Your next line:
element.find_element_by_xpath(".//a").click() #this works and navigates to new page
transitions to a completely new page, as you pointed out in your comment. At this point element
is gone, so the next line:
element.find_element_by_link_text('Click here').click() #this doesn't
has no chance of doing anything as it refers to something that is not there. Which is exactly what the NoSuchElementException
is telling you.
You need to start from the beginning, with something like:
driver.find_element_by_link_text('Click here').click()
Additional answer:
To solve your iteration dilemma, you could take the following approach - please note that I am not familiar with python syntax! The below is Groovy syntax, you will have to adjust it to Python!
// first count the number links you are going to hit; no point in storing this WebElement,
// since it will be gone after we navigate to the first page
def linkCount = driver.findElements(By.className("thumbnail")).size()
// Start a loop based on the count. Inside the loop we are going to have to find each of
// the links again, based on this count. I am going to use XPath; this can probably be done
// on CSS as well. Remember that XPath is 1-based!
(1..linkCount).each {
// find the element again
driver.findElement(By.xpath("//div[@class='thumbnail'][$it]/a")).click()
// do something on the new page ...
// and go back
driver.navigate().back()
}
Turns out you need to store the links you want to navigate to in advance. This is what ended up working for me (found this thread to be helpful):
driver.get(<some url>)
elements = driver.find_elements_by_xpath("//h2/a")
links = []
for i in range(len(elements)):
links.append(elements[i].get_attribute('href'))
for link in links:
print 'navigating to: ' + link
driver.get(link)
# do stuff within that page here...
driver.back()