简体   繁体   English

使用 Python 在 XPATH / Selenium 中找到最后一个 div

[英]Find the last div in XPATH / Selenium with Python

I am new to the subject and my problem is quite simple but I think I am not doing it right: :'(我是这个主题的新手,我的问题很简单,但我认为我做得不对::'(

I'm trying to get the last element of a div because its number is dynamic.我正在尝试获取 div 的最后一个元素,因为它的数字是动态的。 I am using selenium and it goes something like this:我正在使用 selenium 它是这样的:

test = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div/div/div/div/div[2]/div[2]/main/div[1]/div/div[1]/div/**div[17]**/div[2]/div[1]/div/div[2]/div[1]/div[2]/a")

I would like to recover the value of the "div [17]" which will become "div [18]" or later 19 for example.我想恢复“div [17]”的值,例如,它将变为“div [18]”或以后的 19。

I tried something like this but it didn't work:我尝试了这样的事情,但没有奏效:

test = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div/div/div/div/div[2]/div[2]/main/div[1]/div/div[1]/div/**div[last()]**/div[2]/div[1]/div/div[2]/div[1]/div[2]/a")

I'm blocking a bit, thanks for your help:)我有点卡住了,谢谢你的帮助:)

test = driver.find_elements_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div/div/div/div/div[2]/div[2]/main/div[1]/div/div[1]/div/div")

lastelement = test[-1].find_element_by_xpath("./div[2]/div[1]/div/div[2]/div[1]/div[2]/a")

use find elements, it returns full elements and then use -1 to get the last element from the array使用查找元素,它返回完整元素,然后使用 -1 从数组中获取最后一个元素

Have you try this?你试过这个吗? Why is XPath last() function not working as I expect? 为什么 XPath last() function 没有按预期工作?

Perhaps you need to round your div block with parentheses and use the double slash '//(div)[last()]'也许您需要用括号将 div 块四舍五入并使用双斜杠 '//(div)[last()]'

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

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