Cornel Verster
Cornel Verster

Reputation: 1783

Selenium select element by part of class name or by other attribute

I am trying to select multiple elements on a site page with Selenium in Python that has the following structure:

<div class="PodiaMovers js_resultTile" data-listing-number="108376450">
<div class="PodiaAgave js_resultTile" data-listing-number="108342737">
<div class="PodiaButler js_resultTile" data-listing-number="108362396">
etc..

Here, PodiaMovers is a randomly generated string that changes for each element. So I'm thinking I could look for either a portion of the class name ("js_resultTile"), or I could look for the data-listing-number attribute, but I don't know how to do that with Selenium.

Could you help me out?

Upvotes: 0

Views: 297

Answers (2)

mds731
mds731

Reputation: 56

Here is the sample code for you; python as scripting language

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

# initializing chrome driver

driver = webdriver.Chrome("D:\D_Drive\driver\chromedriver") 
           //should be directory path of chrome webdriver


# accessing yahoo home page for example yahoo

driver.get("http://www.yahoo.com")

# print page titile on console

print(driver.title)

try:

# locate the element or timeout

searchResult_Container = WebDriverWait(driver, 10).until(

    EC.presence_of_element_located((By.CLASS_NAME, "js_resultTile"))
)

# --- Now the variable "searchResult_Container" will have the element 
#--- you can perform action using this "searchResult_Container"

finally:

# close web browser window

driver.quit()

}

Upvotes: 0

supputuri
supputuri

Reputation: 14145

If you want to use data-listing-number then you can try the below xpath.

//div[@data-listing-number='108376450']

The line of code will looks like below.

ele = driver.find_element_by_xpath("//div[@data-listing-number='108376450']")
# now you can perform your operation on the ele
ele.click()

If you want to use the js_resultTile then use the below code.

ele = driver.find_element_by_xpath("//div[contains(@class,'js_resultTile')]")
# now you can perform your operation on the ele
ele.click()

To get all the elements that contains js_resultTile use the below.

eles = driver.find_elements_by_xpath("//div[contains(@class,'js_resultTile')]")

Upvotes: 2

Related Questions