Home > Software design >  How to find_elements with multiple attributes using cssSelector Python and Selenium
How to find_elements with multiple attributes using cssSelector Python and Selenium

Time:02-26

I'm trying to find all the elements that have <a href=....> inside the <div id="contents" ...>

Here is the HTML code:

<div id="contents" >
    <div id="dismissible" >
        <a id="thumbnail" href="http://www.test.com">

Here is my python code:

items = driver.find_elements(By.cssSelector("div[id="contents"] a[id="thumbnail"]"))

It gives me the error:

SyntaxError: invalid syntax. Perhaps you forgot a comma?

Where do I need to put the comma?

CodePudding user response:

It's a syntax related error. you are trying to come up with a list of the webelements which contain the different HTML's?

items = driver.find_elements(By.CSS_SELECTOR,"a#thumbnail")

CodePudding user response:

This error message...

SyntaxError: invalid syntax. Perhaps you forgot a comma?

...implies that the css_selector you have used contains a SyntaxError.


Deep Dive

There are two approaches to write as follows:

  • Either you mention the value of the attributes within single quotes i.e. '...' and the entire locator within double quotes i.e. "...". Example:

    "tag_name[attribute_name='attribute_value']"
    
  • Or you mention the value of the attributes within double quotes i.e. "..." and the entire locator within single quotes i.e. '...'. Example:

    'tag_name[attribute_name="attribute_value"]'
    

Solution

To identify all the elements having <a href=....> within <div id="contents" ...> you can use the following locator strategy:

elements = driver.find_elements(By.CSS_SELECTOR, "div[id='contents'] a[href]")

However, incase of css_selector:

  • class attributes can be shortened as .element_class
  • id attributes can be shortened as #element_id

So precisely, your locator strategy can be:

elements = driver.find_elements(By.CSS_SELECTOR, "div#contents a[href]")

Getting Granular

To be more canonical, you may like to consider the id attribute of the <a> element as well i.e. thumbnail. So effectively the locator strategy would be:

elements = driver.find_elements(By.CSS_SELECTOR, "div#contents a#thumbnail[href]")
  • Related