pythonpython-3.xselenium-webdriverselenium-chromedriverfindelement

Finding attribute of elements with same xpath not working


I am attempting to get the title attribute for every listing on a market.

Element:

<a href="/goods/857529?from=market#tab=selling" title="MP9 | Food Chain (Minimal Wear)" xpath="1">

My code:

xpath = "//body/div[@class='marketlist']/div[@class='l_Layout']/div[@id='j_market_card']/div[@id='j_list_card']/ul[@class='card_csgo']/li[1]/a[1]"
for itemName in driver.find_elements("xpath", xpath):
    itemName = itemName.get_attribute("title")
    print(itemName)

Right now only the first element is being located on the page, although all of the other listings share the exact same xpath. Is there any reason the other listings aren't being located?

Also, is there a better way to locate all of the elements than by xpath? I know link text can be used but each title is different, so I wouldn't be able to search by link text.


Solution

  • From the HTML provided, it looks like the CSS selector

    #j_list_card li > a
    ^ # indicates an ID
                ^ a space indicates a descendant
                    ^ a > indicates a child
    

    would work.

    See the W3C spec for a good references on CSS selector syntax.