Yousuf
Yousuf

Reputation: 123

Selenium Python find element partial link text

I'm trying to use Pythons Selenium module to click on an element whose link has the text "xlsx" at the end of it. Below is the code I'm using and the details of the element. Can someone please see why Python is unable to find this element?

driver.find_element_by_partial_link_text('xlsx').click()

Here is the element details:

<a name="URL$2" id="URL$2" ptlinktgt="pt_new" tabindex="43" onfocus="doFocus_win0(this,false,true);" href="http:******/HSC8_CNTRCT_ITEMS_IMPRVD-1479218.xlsx" onclick="window.open('http:********/HSC8_CNTRCT_ITEMS_IMPRVD-1479218.xlsx','','');cancelBubble(event);return false;" class="PSHYPERLINK">HSC8_CNTRCT_ITEMS_IMPRVD-1479218.xlsx</a>

I had to remove some parts of the URL for confidentiality purposes, however, it should not impact the answering of the question.

Thanks.

Upvotes: 1

Views: 3529

Answers (4)

Larry
Larry

Reputation: 226

You can use a CSS selector:

driver.find_element_by_css_selector("a[href*='xlsx']")

If the element still cannot be located, I would suggest using a wait statement, to ensure that the element is visible, before you interact with it.

Upvotes: 1

Yousuf
Yousuf

Reputation: 123

Thanks for the replies. Turns out, as @Andersson mentioned, the window was in a different frame.

I solved the problem using the following code before the find_element: driver.switch_to.frame('ptModFrame_0').

Upvotes: 1

Patrick Harris
Patrick Harris

Reputation: 325

You can grab it by class name (class name = PSHYPERLINK).

This should work:

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

url = ''
driver = webdriver.Chrome('/path/to/chromedriver/executable')

if __name__=='__main__':
     driver.get(url)
     time.sleep(3)
     driver.find_element_by_class_name('PSHYPERLINK').click()

When finding the attribute, make sure to use a singular '"element". Like:

driver.find_element_by_class_name('PSHYPERLINK').click()

not:

driver.find_elements_by_class_name('PSHYPERLINK').click()

Hope this helps.

Upvotes: 0

jaibalaji
jaibalaji

Reputation: 3475

Please try: driver.find_element_by_xpath(".//a[contains(@href,'xlsx')]").

Upvotes: 0

Related Questions