How to Navigate to a New Webpage In Selenium?

前端 未结 2 1447
天命终不由人
天命终不由人 2020-11-27 22:26

I have the following code:

driver.get()
for element in driver.find_elements_by_class_name(\'thumbnail\'):
    element.find_element_by_xpath(\         


        
相关标签:
2条回答
  • 2020-11-27 23:13

    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()
    
    0 讨论(0)
  • 2020-11-27 23:17

    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()
    }
    
    0 讨论(0)
提交回复
热议问题