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 css-selectors 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]")