如何使用selenium和python创建具有相同xpath的元素列表? [英] How can I create a list of elements with the same xpath using selenium with python?

查看:244
本文介绍了如何使用selenium和python创建具有相同xpath的元素列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要单击同一网页上同一表中的几个元素.我当时想使用for循环来执行此操作,但是为了执行该操作,我首先需要创建这些元素的列表.

I need to click on several elements from the same table on the same webpage. I was thinking to do so with a for loop but in order to perform that action I first need to create a list of these elements.

//table[@border='1']//a

这是从表中选择所有元素的xpath,如何创建所有这些元素的列表?

This is the xpath which selects all the elements from the table, how can I create a list of all these?

推荐答案

@SergiyKonoplyaniy答案是正确的方向,一个接一个地解决您的查询:

While @SergiyKonoplyaniy answer was in the right direction, addressing your queries one by one:

  • 如何创建具有相同xpath的元素列表:要创建元素列表,您需要使用

  • How can I create a list of elements with the same xpath : To create a list of elements you need to use find_elements_by_xpath(xpath) which will create a List of elements matching the xpath you have specified.

示例:

my_links = driver.find_elements_by_xpath("//table[@border='1']//a")

  • 需要单击多个元素:由于您需要click()在多个元素上,因此必须遍历在 List 如下:

  • Need to click on several elements: As you need to click() on several elements you have to iterate through all the elements you have captured in the List as follows:

    for link in my_links:
        link.click()
    

  • 现在最重要的方面是,根据您的 xpath //table[@border='1']//a每个元素:

  • Now the most important aspect is, as per your xpath //table[@border='1']//a each and every element:

    • Has 3 distinct stages interms of presence, visibility and interactibility (i.e. clickability)
    • To collect the elements in a List you should always invoke a waiter with expected-conditions as visibility_of_all_elements_located(locator) as follows:

    my_list = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_all_elements_located((By.XPATH, "//table[@border='1']//a")))
    

  • 作为您问题的解决方案的伪代码将是:

  • The pseudo code as a solution for your question will be:

    my_links = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_all_elements_located((By.XPATH, "//table[@border='1']//a")))
    for link in my_links:
        link.click()
    

  • 供以后参考,如果您打算在任何特定元素上调用click(),请始终以 =期望条件作为

  • For your future reference, if you intend to invoke click() on any particular element always invoke a waiter with expected-conditions as element_to_be_clickable(locator) as follows:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "desired_element_xpath"))).click()
    

  • 这篇关于如何使用selenium和python创建具有相同xpath的元素列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆