Create a variable inside an xpath

Asked

Viewed 120 times

0

I’m trying to create an automation in python - (web scraping) that has a loop in which xpath changes every time you click on the desired location, so I realized that xpath only changes one digit:

//*[@id="j_id184:dados:0:j_id306"]
//*[@id="j_id184:dados:1:j_id306"]
//*[@id="j_id184:dados:2:j_id306"]

You could put that number as a variable?
Or is there another way to do it?

code considering only one object:

self.webDriverWait(self.driver,15).until(self.ec.element_to_be_clickable((self.by.XPATH,'//[@id="j_id184:dados:0:j_id306"]')))
click_nfs = self.driver.find_element_by_xpath('//*[@id="j_id184:dados:0:j_id306"]')

2 answers

0


You can use to format the string. For this purpose the python strings have a method called format.

Follow an example:

format_xpath = '//*[@id="j_id184:dados:{numero}:j_id306"]'

for i in range(10):
    # para cada interacao o valor de numero é alterado
    # Exemplo quando i vale 0: '//*[@id="j_id184:dados:0:j_id306"]'
    # Exemplo quando i vale 1: '//*[@id="j_id184:dados:1:j_id306"]'
    # Exemplo quando i vale 9: '//*[@id="j_id184:dados:9:j_id306"]'
    xpath = format_xpath.format(numero=i)
    print(xpath)
    element = self.driver.find_element_by_xpath(xpath)
    element.click()
  • That’s exactly what I was looking for, thank you very much!

0

You can format the xpath string. Examples:

click_nfs = self.driver.find_element_by_xpath(f'//*[@id="j_id184:dados:{n}:j_id306"]')

or

click_nfs = self.driver.find_element_by_xpath('//*[@id="j_id184:dados:%d:j_id306"]' % n)

where n is the number you’re in.

  • Thank you! That’s what I needed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.