GeratTheGreat
GeratTheGreat

Reputation: 1

Trouble using selenium to click an item by partial link text

So I made a script a few years back that would use selenium to navigate a store, locate items by their name, then select them. I was trying to re-make it looking at my old code but it isn't working the same. I'm trying to use selenium to click on the first item it finds containing the text they have when I use inspect element on the item. However I just keep getting the same error that it can't find an element containing that text.

from selenium import webdriver

driver=webdriver.Chrome('fakepath/fake')
driver.get("https://www.supremenewyork.com/shop/all")

driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click()
driver.find_element_by_partial_link_text('GORE-TEX')

Here's the element containing the text that I'm trying to use selenium to find and click on

<a class="name-link" href="/shop/jackets/g1ze294ol/qapno01c2">GORE-TEX Taped Seam Jacket</a>
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"GORE-TEX"}
  (Session info: chrome=76.0.3809.132)

Upvotes: 0

Views: 1940

Answers (2)

fendall
fendall

Reputation: 524

The element you are trying to click is not ready to be clicked when the line driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click() is executed. In other words, you need to wait until the element is loaded.

Luckily, Selenium allows you to wait for certain conditions, such as "clickable". See here for reference.

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

driver=webdriver.Chrome('fakepath/fake')
wait = WebDriverWait(driver, 10)

driver.get("https://www.supremenewyork.com/shop/all")

try:
    wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@href='/shop/all/jackets']")).click()
    driver.find_element_by_partial_link_text('GORE-TEX')
finally:
    driver.quit()

Upvotes: 0

Sureshmani Kalirajan
Sureshmani Kalirajan

Reputation: 1938

You need to wait until the element is clickable. This will click on the first matching link on the page.

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


driver.get("https://www.supremenewyork.com/shop/all")
driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click()

link = WebDriverWait(driver,15).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "GORE-TEX")))
link.click()
time.sleep(3)

Upvotes: 1

Related Questions