1

I am right now learning Selenium via python webdriver with Chrome web-browser. I have written a test as in the course and I have got error Will be glad if anyone can help please:

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:\Python27\chromedriver.exe")
driver.maximize_window()
driver.get("https://makemytrip.com")
driver.find_element_by_css_selector("label[for='fromCity']").click()
driver.find_element_by_css_selector("input[placeholder='From']").send_keys("Del")
cities =driver.find_elements_by_css_selector("p[class*='blackText']")
for city in cities
    if city.text =="Del Rio, United States":
        city.click()

The error appears to be next to cities in line 9. thanks.

2

5 Answers 5

1

you are simply missing the ":" at the end of your for loop in line 9.

for city in cities:

If thats not the fix but just a typo you should post the error message :)

1
  • selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=80.0.3987.122) Commented Mar 12, 2020 at 10:19
1

The problem is that you're clicking on a WebElement which may have updated your web-page, and then you're trying to click on the next WebElement (in the for loop) which will fail since your page has been updated.

So all you need to is, get all elements every time you update the page

Try this:

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:/Python27/chromedriver.exe")
driver.maximize_window()
driver.get("https://makemytrip.com")
driver.find_element_by_css_selector("label[for='fromCity']").click()
driver.find_element_by_css_selector("input[placeholder='From']").send_keys("Del")

idx = 0
cities = lambda: driver.find_elements_by_css_selector("p[class*='blackText']")
while idx < len(cities()):
    driver.implicitly_wait(1000)
    city = cities()[idx]
    if city.text =="Del Rio, United States":
        city.click()
    idx += 1
0

try this

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:/Python27/chromedriver.exe")
driver.maximize_window()
driver.get("https://makemytrip.com")
driver.find_element_by_css_selector("label[for='fromCity']").click()
driver.find_element_by_css_selector("input[placeholder='From']").send_keys("Del")
cities =driver.find_elements_by_css_selector("p[class*='blackText']")
for city in cities:
    driver.implicitly_wait(1000)
    if city.text =="Del Rio, United States":
        city.click()

add some delay to let the the dropdown to load otherwise it gives another error

1
  • This gets the same result as I get Commented Mar 12, 2020 at 11:28
0

Thank you guys. I have managed to solve this problem. Del Rio didn't appear in the results of the search, this is way I couldn't have chosen this option.

0

missing colon (':') it should be - for city in cities:

Not the answer you're looking for? Browse other questions tagged or ask your own question.