I am struggling to click the first href that matches a keyword. There is at least 2 hrefs that match a keyword im using so selenium fails at clicking the element. I have tried to nominate the class and look inside that class for the Href but the syntax is incorrect. I currently have this code in a try block as it refreshes if the href is not found and tries again.
see below:
<div class="productitem--info">
<span class="productitem--vendor">
GlenWyvis</span>
<h2 class="productitem--title">
<a href="/collections/new-whisky-arrivals/products/glenwyvis-batch-20-18-2018-vintage-2nd-release" data-product-page-link="">
GlenWyvis Batch 02/18 | 2nd Release
</a>
</h2>
The Python try block I have is below:
while True:
try:
element = driver.find_element(By.XPATH, "//*[@class='productitem--title'] and contains(.@href, 'glenwyvis')]")
element.click()
break
except NoSuchElementException:
driver.refresh()
time.sleep(3)
Any help is greatly appreciated.
Many thanks.
With minimal modifications, you could use
element = driver.find_element(By.XPATH, "//*[@class='productitem--title' and contains(a/@href, 'glenwyvis')]")
This returns the <h2>
element with the desired properties.