简体   繁体   English

通过 xpath 在 Python 中查找元素

[英]Finding element in Python by xpath

I am trying to click on an item whose xpath is:我正在尝试单击 xpath 为的项目:

//*[@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.还有更多以//*[@id="single"]开头的元素,并且每次页面加载时数字都会更改。 So the only specific bits are the combination of "single" and /div[2]/div[1].所以唯一的特定位是“single”和/div[2]/div[1].

The CSS_selector has the number as well, so it is of no use. CSS_selector 也有编号,所以没用。

What would the code to select the element be? select 元素的代码是什么?

I'm using Python and Selenium.我正在使用 Python 和 Selenium。

Here, I am assuming that you want to click all the elements that has the combination of "single" and /div[2]/div[1].在这里,我假设您要单击具有“single”和/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.首先,尝试从所需元素的父元素中获取所有元素。现在您将留下 WebElements 列表。遍历所有元素并单击 id 以单个开头的元素。

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.试试这个 xpath,让我知道它是怎么回事。

(//*[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下面的 xpath 将帮助您找到包含单个 id 值的所有元素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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