r/automatewithpython • • Jul 20 '20

Cannot iterate through buttons in web element list with Selenium

1 Upvotes

I am trying to iterate clicking through the North American cities in the Uber Movement data.

I have setup Python code to select the table of all cities (cities_table), make it into a list, and identify the button for each city to be clicked (the button has a tag name 'a').

My problem is that I am able to select the first city in the table (Atlanta), but when I try to go back to the page with the table of all cities I do not manage to click on the next city on the list, which should be Boston.

After I successfully enter the Atlanta page, I setup a driver.back() to go back to the cities table, but when trying to move on to the next item on the list, I get the following error message:

Message: stale element reference: element is not attached to the page document

How can I correctly click on a city, go back to the cities table page and click on the NEXT item?

Here is my code so far:

# Load Chrome driver and movement.uber.com/cities website
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://movement.uber.com/cities?lang=en-US')
# City loop
cities_table = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[1]/div[2]/div[1]/div')
cities = cities_table.find_elements_by_tag_name('div') for city in cities:
    city = city.find_element_by_tag_name('a') # Buttons have tags "a"
    city.click()
    time.sleep(3)
    driver.back()

Full error message below:

StaleElementReferenceException Traceback (most recent call last) <ipython-input-25-a148ef184a6b> in <module> 6 cities = cities_table.find_elements_by_tag_name('div') 7 for city in cities: ----> 8     city = city.find_element_by_tag_name('a') # Buttons have tags "a" 9     city.click() 10     time.sleep(3) ~\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webelement.py in find_element_by_tag_name(self, name) 303             element = element.find_element_by_tag_name('h1') 304 """ --> 305         return self.find_element(by=By.TAG_NAME, value=name)     306      307     def find_elements_by_tag_name(self, name):  ~\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webelement.py in find_element(self, by, value)     657      658         return self._execute(Command.FIND_CHILD_ELEMENT, --> 659                              {"using": by, "value": value})['value']     660      661     def find_elements(self, by=By.ID, value=None):  ~\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webelement.py in _execute(self, command, params)     631             params = {}     632         params['id'] = self._id --> 633         return self._parent.execute(command, params)     634      635     def find_element(self, by=By.ID, value=None):  ~\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)     319         response = self.command_executor.execute(driver_command, params)     320         if response: --> 321             self.error_handler.check_response(response)     322             response['value'] = self._unwrap_value(     323                 response.get('value', None))  ~\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)     240                 alert_text = value['alert'].get('text')     241             raise exception_class(message, screen, stacktrace, alert_text) --> 242         raise exception_class(message, screen, stacktrace)     243      244     def _value_or_default(self, obj, key, default):  StaleElementReferenceException: Message: stale element reference: element is not attached to the page document   (Session info: chrome=84.0.4147.89)

r/automatewithpython • • May 19 '20

Chapter 6 - Table Printer Project help

1 Upvotes

Hello! I'm new to python, kind of new to coding. Below is the code I've got that works for finding the longest string in the nested lists, but then when it needs to print the lists as justified columns, it only does the first 3 strings of the first list then putters out to an index error. I see that I should make the while loop go longer, but I'm not sure how to do that and not get a different error. The problem I have is the code after

b = 0

Thanks for your help

#! python3

import pyperclip
import random
import sys

'''write a function that takes a list of strings and displays it in a well-
    organized table with each column right-justified. assume inner lists
    will have the same number of strings'''

tableData = [['apples', 'oranges', 'cherrrrrrries', 'banana',],
             ['Alice', 'Bobbbbbbbbbbbb', 'Carol', 'David'],
             ['dogssss', 'cats', 'moose', 'goose']]

def printTable(tbl):
    colW=[0]*len(tbl)   #[0,0,0]
    for i in range(len(tbl)):
        a = 0
        for j in range(len(tbl[i])):
            if a < len(tbl[i][j]):
                a = len(tbl[i][j])
            colW[i] = a
    print(colW)                     #[13, 14, 7] which is correct
    b = 0
    while b < len(tbl):
        for c in range(len(tbl[b])):
            print(str(tbl[b][c]).rjust(colW[c])+'\n')
        
printTable(tableData)

EDIT:

I found something on stackoverflow. So my issue was trying to make a function that could do the required tasks with a data table of any size with the nested lists being over varying lengths. That's probably why i was getting all wound up. Using only what has been taught in the book so far it is probably impossible to do so. I was able to make it work, but only if the nested lists are of equal length, which feels like cheating...

tableData = [['apples', 'oranges', 'cherrrrrrries', 'banana',],
             ['Alice', 'Bobbbbbbbbbbbb', 'Carol', 'David'],
             ['dogssss', 'cats', 'moose', 'goose']]

def printTable(tbl):
    colW=[0]*len(tbl)   #[0,0,0]
    for i in range(len(tbl)):
        a = 0
        for j in range(len(tbl[i])):
            if a < len(tbl[i][j]):
                a = len(tbl[i][j])
            colW[i] = a
##    print(colW)                     #[13, 14, 7] which is correct
    
    for i in range(len(tbl[0])):
        ntbl=[]
        for j in range(len(tbl)):
            ntbl.append(str(tbl[j][i]).rjust(colW[j]))
        print(' '.join(ntbl))
            
        
printTable(tableData)

r/automatewithpython • • Mar 24 '20

How to create Beautiful HTML Apps with Python using eel.

Thumbnail
youtube.com
1 Upvotes

r/automatewithpython • • May 10 '15

Regex Version of Strip()

1 Upvotes

Hi Guys,

Could you help me out with the chapter 7 practice project?

I googled on defining functions with one or more optional arguments and came up with the code below

    import re

sentence = '             The quick fox jumped       '



def regstrip(sentence,char = ''):
 
        wSpaceRegex = re.compile(r'^\s+(\w)')
        mo = wSpaceRegex.sub(r'\1', sentence)

        wSpaceRegex = re.compile(r'(\w)\s+$')
        mp = wSpaceRegex.sub(r'\1', mo)

        print(mp)

        wSpaceRegex = re.compile(char)
        mo = wSpaceRegex.sub('a', sentence)


        print(mo)



regstrip(sentence,'u')

I'm sure there's a slightly cleaner way to write the code but it seems to work and strip out the white spaces at the beginning and end. And also replace a character given as the 2nd argument.

What I can't figure out (and have tried looking online) is how to add the code that only makes the function do either one of the strips/sub without doing the other.

Thanks