相关文章推荐

如何在Selenium python中找到相同divs内的最后一个元素

1 人关注

我正在尝试使用 selenium 找到一个 div 内的最后一个元素,将其打印到控制台并等待下一个元素的生成。我已经尝试了for和while循环,但它们不起作用。我希望每次都能选择最后一个。

在下面的例子中。

    <div class="row">
        <div class="col">
            This is the first text
    <div class="row">
        <div class="col">
            This is the second text

我想找到每次This is the second text,如果产生另一个This is the third text,以此类推。我已经试过了,但它并不奏效。【替换代码3

请至少用python编写这个循环的伪代码。

如何写一个简单的Python代码,获得最后一个文本并将其打印到控制台。然后等待,直到另一个文本产生,如此循环。

python
html
python-3.x
selenium
xpath
Aayush Khawaja
Aayush Khawaja
发布于 2020-03-14
2 个回答
Sameer Arora
Sameer Arora
发布于 2020-03-14
已采纳
0 人赞同

你可以使用xpath获取一个列表中的所有元素,然后使用该列表的 [-1] 索引获取该列表中的最后一个元素。
你可以像这样做。

# Fetching all the elements in a list
WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, "//div[@class='col']")))
text_list = driver.find_elements_by_xpath("//div[@class='col']")  
# Fetching the text of last element
last_text = text_list[-1].text
    
IndexError: list index out of range
@AayushKhawaja已经编辑了我的答案,请现在查看。
rmontanodev
rmontanodev
发布于 2020-03-14
0 人赞同
 
推荐文章