Timeout error on selecting the first item in unittest Python

Question:

I’m trying to create a unittest using Selenium Webdriver on Python. This test aims to search for a given item, search the first result, add it to the cart and check that there is one product. However, I cannot get this done. Below is my code:

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class EtsyTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        
    def tearDown(self):
        self.driver.quit()
        
    def test_add_to_cart_etsy(self):
        self.driver.get("https://www.etsy.com/")
        wait = WebDriverWait(self.driver, 10)
        search_field = wait.until(EC.visibility_of_element_located((By.ID, "global-enhancements-search-query")))
        search_field.send_keys("handmade jewelry")
        search_field.send_keys(Keys.RETURN)
        first_item = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@class='listing-link'][1]")))
        first_item.click()
        add_to_cart_button = wait.until(EC.visibility_of_element_located((By.XPATH, "//button[@data-action='add-to-cart']")))
        add_to_cart_button.click()
        assert "1 item in your cart" in self.driver.page_source

if __name__ == "__main__":
    unittest.main()

I get this error:

first_item = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@class='listing-link'][1]")))
  File "C:Usersanaconda3libsite-packagesseleniumwebdriversupportwait.py", line 95, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Asked By: GoT GOt

||

Answers:

For your error, it just happens you are using wrong xpath…

Try this:

//ol[@class='wt-grid wt-grid--block wt-pl-xs-0 tab-reorder-container']/*[1]

I’m sure there are better and shorter versions of this, but that is up to you to figure out!

P.S (even after this step your code doesn’t work xd)

Answered By: RifloSnake