1

If I select flight departure time with class name through selenium in python but class name is used by both div & span tags it fails.

How can I select only one element type (div) and not sdpans.

my code is:

[element.text for element in self.browser.find_elements(By.CLASS_NAME, "dept-time")]
3

To select the div with the class you can use css (preferred for readability)

BY.css

Example

driver.find_element(By.CSS, 'div.dept-time')

or xpath

BY.xpath

Example

driver.find_element(By.XPATH, '//div[@class=dept-time]

or if there are multiple classes for that element, use

contains

Example

//div[contains(@class, 'dept-time')]

If more than 1 div element with that class exist and you want the first one you can also use:

[1]

Example (XPATH)

//div[@class='dept-time'])[1]

Example (CSS)

div.dept-time:first
  • 1
    i want to select only div tag through class name but i run my API its scraps both data because class name is same in both tag then how to select only div class name. <div class="dept-time">11:10</div> not <span class="dept-time">11:10</span> – Technical Gyan May 4 at 12:46
  • 1
    Yes my code here select only div's as shown What do you not understand about it? – Michael Durrant May 4 at 12:49
  • Are you getting a multiple matches error and assuming it is finding div's as well as span's perhaps ? If so it will be because there are multiple div's with that class (class is a clue too as classes are applied to multiple elements where as id's are unique). – Michael Durrant May 4 at 12:50
0

Using css selectors, instead of class, the syntax to select the tag with a specific class/attribute is tag[attribute='value']. So in your case:

[element.text for element in self.browser.find_elements(By.CSS_SELECTOR, "div[class='dept-time']")]

More information on css selectors: https://www.w3schools.com/cssref/css_selectors.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.