如何通过Selenium使用xpath定位元素

如何通过Selenium使用xpath定位元素,selenium,selenium-webdriver,xpath,webdriver,xpath-1.0,Selenium,Selenium Webdriver,Xpath,Webdriver,Xpath 1.0,如何通过Selenium使用xpath定位元素 代码试用: By.xpath("//*[contains(@class,'a-size-mini a-spacing-none a-color-base s-line-clamp-2') and contains(text(), \"Men's Downshifter 9 Training Shoes\")]")); HTML: 关闭] 备选方案: //h2[.=“男式9档降档训练鞋”] //span[.=“男式降档9号训练鞋”]/祖先::h2

如何通过Selenium使用xpath定位元素

代码试用:

By.xpath("//*[contains(@class,'a-size-mini a-spacing-none a-color-base s-line-clamp-2') and contains(text(), \"Men's Downshifter 9 Training Shoes\")]"));
HTML:

关闭]

备选方案:

//h2[.=“男式9档降档训练鞋”] //span[.=“男式降档9号训练鞋”]/祖先::h2[1] //h2[./a[.=“男式降档9号训练鞋”]]
要定位图元,可以使用以下任意一种方法:

使用xpath和文本:

使用xpath并包含:

使用xpath和父标记:

By.xpath("//*[contains(@class,'a-size-mini a-spacing-none a-color-base s-line-clamp-2') and contains(text(), \"Men's Downshifter 9 Training Shoes\")]]"));
By.xpath("//span[text()=\"Men's Downshifter 9 Training Shoes\"]"));
By.xpath("//span[@class='a-size-base-plus a-color-base a-text-normal' and contains(., 's Downshifter 9 Training Shoes')]"));
By.xpath("//a[@class='a-link-normal a-text-normal' and starts-with(@href, '/Nike-Downshifter-Running-Shoes-Anthracite/dp/')]/span[@class='a-size-base-plus a-color-base a-text-normal' and contains(., 'Downshifter 9 Training Shoes')]"));