简体   繁体   中英

Finding element in Python by xpath

I am trying to click on an item whose xpath is:

//*[@id="single-71048602500"]/div[2]/div[1]

There are more elements that start with //*[@id="single"] , and the number changes each time the page loads. So the only specific bits are the combination of "single" and /div[2]/div[1].

The CSS_selector has the number as well, so it is of no use.

What would the code to select the element be?

I'm using Python and Selenium.

Here, I am assuming that you want to click all the elements that has the combination of "single" and /div[2]/div[1].

First, try to get all the elements from the required element's parent element.Now you'd be left with list of WebElements.iterate through all elements and click elements whose id starts with single.

sd = mainpage.find_elements_by_xpath('//*[@id]') #parent webelement
for i in sd:

        if str(i.get_attribute('id')).startswith("single"):

             j = i.find_element_by_xpath('//*[@id="{}"]/div[2]/div[1]'.format(i.get_attribute('id')))
             j.click()

Try this xpath and let me know how it goes.

(//*[contains(@id,"single")]/div[2]/div[1])[index of an element ]

The below xpath will help you to find all the element which is contains id values as single

//*[contains(@id,"single")]/div[2]/div[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM