python selenium xpath_如何使用selenium和python创建具有相同xpath的元素列表?

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

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

解决方案

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

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.

Example:

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

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()

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()

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值