Loop through links using Selenium Webdriver (Python) -


afternoon all. trying use selenium webdriver loop through list of links on page. specifically, it's clicking link, grabbing line of text off said page write file, going back, , clicking next link in list. following have:

    def test_text_saver(self):     driver = self.driver     textsave = open("textsave.txt","w")     list_of_links = driver.find_elements_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[2]/div/div/ul/li")     """initializing link count:"""     link_count = len(list_of_links)     while x <= link_count:         print x         driver.find_element_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[2]/div/div/ul/li["+str(x)+"]/a").click()         text = driver.find_element_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[1]/div[1]/h1").text         textsave.write(text+"\n\n")         driver.implicitly_wait(5000)         driver.back()         x += 1     textsave.close() 

when run, goes initial page, and...goes main page, rather subpage it's supposed to. printing x, can see it's incrementing 3 times rather one. crashes after that. i've checked xpaths , such, , confirmed it's getting correct count number of links in list.

any input's hugely appreciated--this flex python/automation, since i'm getting both. in advance!!

i'm not sure if fix problem, in general better use webdriverwait rather implicitly_wait since webdrivewait.until keep calling supplied function (e.g. driver.find_element_by_xpath) until returned value not false-ish or timeout (e.g 5000 seconds) reached -- @ point raises selenium.common.execptions.timeoutexception.

import selenium.webdriver.support.ui ui  def test_text_saver(self):     driver = self.driver     wait = ui.webdriverwait(driver, 5000)     open("textsave.txt","w") textsave:         list_of_links = driver.find_elements_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[2]/div/div/ul/li/a")         link in list_of_links:  # 2             link.click()   # 1             text = wait.until(                 lambda driver: driver.find_element_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[1]/div[1]/h1").text)             textsave.write(text+"\n\n")             driver.back() 
  1. after click link, should wait until linked url loaded. call wait.until placed directly after link.click()
  2. instead of using

    while x <= link_count:     ...     x += 1 

    it better use

    for link in list_of_links:  

    for 1 think, improves readability. moreover, don't need care number x, care looping on links, for-loop does.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -