RJA
RJA

Reputation: 13

Selenium web driver code in python for clicking an image

I need a help in python code so that I can have click event on image as Sony using selenium webdriver. I am new to selenium web driver & python. Please note that after clicking on "Testing Inc." image, next page is having login details will be displayed.

Here is the Javascript code:-

<div class="idpDescription float"><span class="largeTextNoWrap indentNonCollapsible">Sony Inc.</span></div> <span class="largeTextNoWrap indentNonCollapsible">Sony Inc.</span> 

Python code written by me but click event is not happening on clicking the image:-

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

# get the path of IEDriverServer 
dir = os.path.dirname(file) 
Ie_driver_path = dir + "\IEDriverServer.exe"
#create a new IE session 
driver = webdriver.Ie("D:\SCripts\IEDriverServer.exe") 
driver.maximize_window()
#navigate to the application home page 
driver.get("example.com") 
element=driver.find_element_by_partial_link_text("Testing Inc.").click();

Upvotes: 1

Views: 360

Answers (2)

Striter Alfa
Striter Alfa

Reputation: 1577

When you search using by_partial_link_text, Selenium expects text inside an a html tag. Since it is inside a span, it will not find it.

What you can do:

  1. Write a Css selector to find the tag that contains the desired image using only tags and attributes. Here you need to check the whole HTML. Since I don't have access to that, I can only assume the below example.

    div.idpDescription span
    
  2. Write an XPath based on the text content. XPath may be more difficult for you to understand since you are not used to developing with Selenium.

    //span[text()='Sony Inc.']
    

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193088

As per the HTML you have shared and your code trial as you are trying to invoke click() on the WebElement with text as Sony Inc. you need to induce WebDriverWait for the element to be clickable as follows :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='idpDescription float']/span[@class='largeTextNoWrap indentNonCollapsible']"))).click()

You can get more granular adding the Link Text to the xpath as follows :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='idpDescription float']/span[@class='largeTextNoWrap indentNonCollapsible' and contains(.,'Sony Inc.')]"))).click()

Upvotes: 0

Related Questions