Home > Enterprise >  Problems extracting elements by class names with Selenium
Problems extracting elements by class names with Selenium

Time:12-18

From this page: enter image description here

I'm trying to extract all elements of class css-1uuzwjq eq4or9x0 into a list in order to click on the elements and further explore.

I have this code, in which I try to get the elements by their Xpath:

ads = browser.find_elements_by_class_name('css-1uuzwjq eq4or9x0')
for ad in ads:
    ad.click()

However, the list always ends up empty. What am I doing wrong?

CodePudding user response:

//div[@class='list']/div[./header[contains(@class,'featured')]]

I would use this xpath to obtain all the divs needed to search.

use /div/header/a if you want the a tag to click.

So it would be

driver.get('https://www.realestate.com.kh/buy/')
hrefs=[x.get_attribute('href') for x in driver.find_elements(By.XPATH,"//div[@class='list']/div/header/a")]
print(hrefs)
for href in hrefs:
    driver.get(href)

Would retrieve all the hrefs to loop and will prevent using driver.back() and all the stale elements you will get.

I would not recommend getting by class name because they seem dynamic also those are multiple class names which are grabbed by a css selector.

css-1uuzwjq eq4or9x0 -> .css-1uuzwjq.eq4or9x0

CodePudding user response:

class attribute holds multiple classes , each class is separated by space. In your case, 'css-1uuzwjq eq4or9x0' are two classes not one

you can find it as :#

  • xpath

in xpath it validates the class attribute value is exactly the same

//*[@] 
  • CSS

in css it checks for element that contains both the mentioned class, each class should be mentionedwith a dot

.css-1uuzwjq.eq4or9x0 

if you want exact match , use the below locator as it checks the class attribute value to be exact

[]
  • using class locator

    browser.find_elements_by_class_name('css-1uuzwjq.eq4or9x0')

calss locator uses css locator under the hood , so when you pass a class name, it just adds 'dot' in front of it . so to make it a valid locator pass all classes by replacing space with dot

  • Related