checkmate
checkmate

Reputation: 11

how to iterate actions in selenium python

I have found webelement using xpath text and performed some actions after finding the webelement. the webelement is in a dropdown. Its a big dropdown with more than 500 options in it. Now I want to perform same set of actions for every webelement which is found using the xpath text I have mentioned.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()

driver.get("url")
driver.find_element_by_xpath("//*[contains(text(), 'abc')]")
driver.find_element_by_xpath("//*[@id='btnsubmit']").click()
driver.find_element_by_xpath("//*[@src='Images/pdf.jpg']").click()

with this code I am able to locate the drop down element which has text abc in it and download the pdf file which appears after clicking the submit button. Now I want to loop this and find other elements which have abc in it and download pdfs for each dropdown element.

I have tried this:

element = driver.find_element_by_xpath("//*[contains(text(), 'abc')]")

for i in element :
  element.click()
  driver.find_element_by_xpath("//*[@id='btnsubmit']").click()
  driver.find_element_by_xpath("//*[@src='Images/pdf.jpg']").click()

but this only finding the first element in the dropdown and downloading the pdf. I want to iterate this for all the elements that have abc text in it and download the pdf.

Also tried this:

element = driver.find_elements_by_xpath(".//*[contains(text(), 'abc')]")

for i in element :
  i.click()
  driver.find_element_by_xpath("//*[@id='btnsubmit']").click()
  driver.find_element_by_xpath("//*[@src='Images/pdf.jpg']").click()

it returns an exception that click cannot be performed on list.

can anyone help me with this problem? it would help me reduce a lot of manual work of clicking on each drop down element and downloading the pdf.

Upvotes: 1

Views: 46

Answers (1)

Rajagopalan
Rajagopalan

Reputation: 6064

You should use i.click instead of element.click there.Or use the below code

elements = driver.find_elements_by_xpath(".//*[contains(text(), 'abc')]")

for element in elements:
    element.click()
    driver.find_element_by_xpath("//*[@id='btnsubmit']").click()
    driver.find_element_by_xpath("//*[@src='Images/pdf.jpg']").click()

Here I have given the name element so it would work.

Upvotes: 0

Related Questions