So I'm starting to get the hang of while loops, however when using the while loop on a selenium code, I come up short.
Pretty much I'm trying to replicate a task 10 times, here is what the code looks like
Main.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://orlando.craigslist.org/search/cta')
owl = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
res = 1
while res < 10:
owl2 = owl.click()
driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
res = res + 1
here is the error
Traceback (most recent call last): File "main.py", line 12, in owl2 = owl.click() File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 77, in click self._execute(Command.CLICK_ELEMENT) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 491, in _execute return self._parent.execute(command, params) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 238, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=56.0.2924.87) (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.11.2 x86_64)
Any Suggestions ?
Every time the DOM is changing or refreshing the driver
losses the elements it previously located witch cause the error.
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
You need to relocate them in order to interact with them. In addition, click()
doesn't returns any value so you can't assign it to anything
res = 1
while res < 10:
owl = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
owl.click()
driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
res = res + 1
Edit
With for
loop for all the items you can locate the items into a list and click by index
size = len(driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a'))
for i in range(0, size):
owl = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
owl[i].click()
driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With